我在使用重写的equals方法时,ArrayList无法正确运行。我的问题是,我想只测试单个关键字段,使用ArrayList.contains()来测试是否存在具有正确字段的对象。下面是一个例子:
public class TestClass {
private static class InnerClass{
private final String testKey;
//data and such
InnerClass(String testKey, int dataStuff) {
this.testKey =testKey;
//etc
}
@Override
public boolean equals (Object in) {
System.out.println("reached here");
if(in == null) {
return false;
}else if( in instanceof String) {
String inString = (String) in;
return testKey == null ? false : testKey.equals(inString);
}else {
return false;
}
}
}
public static void main(String[] args) {
ArrayList<InnerClass> objectList = new ArrayList<InnerClass>();
//add some entries
objectList.add(new InnerClass("UNIQUE ID1", 42));
System.out.println( objectList.contains("UNIQUE ID1"));
}
}
让我担心的是,输出不仅是错误的,而且也没有得到“到这里了”的输出。
有人知道为什么这个覆盖被完全忽略了吗?是否有一些关于覆盖和内部类的微妙之处我不知道的?
编辑: 由于网站出现问题,我无法标记答案。 感谢您的快速回复:是我的疏忽,调用的是String .equals而不是我的自定义方法。我想现在先使用老式检查方式。