我想对对象进行更深入的字符串检查,以便能够执行以下操作:
List<MyObj> myList = new ArrayList<MyObj>() {{
add(new MyObj("hello"));
add(new MyObj("world"));
}};
System.out.println(myList.contains("hello")); // true
System.out.println(myList.contains("foo")); // false
System.out.println(myList.contains("world")); // true
但是用下面的完整代码在每一个上都得到错误
/* Name of the class has to be "Main" only if the class is public. */
class Ideone {
public static class MyObj {
private String str;
private int hashCode;
public MyObj(String str) {
this.str = str;
}
public @Override boolean equals(Object obj) {
System.out.println("MyObj.equals(Object)");
if (obj == this) {
return true;
}
if (obj instanceof String) {
String strObj = (String) obj;
return strObj.equals(str);
}
return false;
}
public @Override int hashCode() {
if (hashCode == 0) {
hashCode = 7;
for (int i = 0; i < str.length(); ++i) {
hashCode = hashCode * 31 + str.charAt(i);
}
}
return hashCode;
}
}
public static final MyObj obj1 = new MyObj("hello");
public static final MyObj obj2 = new MyObj("world");
public static void main (String[] args) throws java.lang.Exception {
List<MyObj> myList = new ArrayList<MyObj>() {{
add(obj1);
add(obj2);
}};
System.out.println(myList.contains("hello"));
System.out.println(myList.contains("foo"));
System.out.println(myList.contains("world"));
}
}
如果我是对的,列表对象应该使用 equals()
和 hashCode()
来计算包含的对象。
所以我 @Override
它们并另外检查它们的字符串。
但它永远不会进入 equals()
,因为没有输出 MyObj.equals(Object)
。
最佳答案
java.util.ArrayList#indexOf
在 ArrayList 内部用于 contains()
。
有一张支票,
o.equals(elementData[i])
因此存在字符串与您的对象的比较,因此调用 String.equals()
来检查是否相等。
关于java - 使用 Java ArrayList contains() 评估包含字符串的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19451212/