Java 如何直接在类而不是集合上调用contains

Java 如何直接在类而不是集合上调用contains,java,contains,Java,Contains,我想知道如何能够直接在我的类上调用contains方法,而不是在它的ArrayList变量上。最好的解释方法是使用下面的代码 谢谢你的帮助 public class Chord { ArrayList<Note> notes; // some more stuff not here } cmaj = new Chord("Cmaj"); cnote = new Note("C"); // what I have cmaj.getNotes().contains(c

我想知道如何能够直接在我的类上调用
contains
方法,而不是在它的ArrayList变量上。最好的解释方法是使用下面的代码

谢谢你的帮助

public class Chord {
    ArrayList<Note> notes;
    // some more stuff not here
}

cmaj = new Chord("Cmaj");
cnote = new Note("C");

// what I have
cmaj.getNotes().contains(cnote);

// what I would like, is this possible, how?
cmaj.contains(cnote);
公共类和弦{
ArrayList注释;
//还有一些东西不在这里
}
cmaj=新和弦(“cmaj”);
CNOT=新票据(“C”);
//我所拥有的
cmaj.getNotes()包含(cnote);
//我想要的是,这可能吗,怎么可能?
cmaj.包含(CNOT);

您可以自己编写方法:

public class Chord {
    private final List<Note> notes;

    ...

    public boolean contains(Note note) {
        return notes.contains(note);
    }
}
公共类和弦{
非公开最后名单说明;
...
公共布尔包含(注){
返回注释。包含(注释);
}
}

这是代理方法的典型示例()

公共类和弦{
私有最终列表注释=新建ArrayList();
公共布尔包含(注){
返回注释。包含(注释);
}
}
当您使用这种类型的方法时,应该在将对象交付给客户机之前仔细检查是否设置了引用。如果你不注意,你会得到NullPointerException。并尽量保持一致,如果您决定以这种方式使用contains,
添加
删除
重置
。然后就不再需要getter了

在chord中编写一个方法contains(),该方法仅将调用委托给arraylist,如下所示:

public class Chord {
    ArrayList<Note> notes;

    public boolean contains(Object o) {
       return notes.contains(o);
    }
}
公共类和弦{
ArrayList注释;
公共布尔包含(对象o){
返回说明。包含(o);
}
}

添加一个方法
contains
封装arrayList的contains:

public class Chord {
    ArrayList<Note> notes;
    // some more stuff not here

    public boolean contains(Note note){
        return notes.contains(note);
    }
}
公共类和弦{
ArrayList注释;
//还有一些东西不在这里
公共布尔包含(注){
返回注释。包含(注释);
}
}

作为一个完全独立的主题,将
注释作为一个类而不是一个类(假设只有13个可能的注释)可能更有意义。对于手头的项目来说,将其作为一个类是有意义的,因为有更多的相关方法。这只是一个很短的片段。谢谢你的建议
public class Chord {
    ArrayList<Note> notes;
    // some more stuff not here

    public boolean contains(Note note){
        return notes.contains(note);
    }
}