您必须覆盖 MyClass 中的等于。
根据您想要实现的目标,您的 equals 方法如下所示:
public boolean equals(Object o) {
if (o== null) return false;
if (!(o instanceof MyClass)) return false;
MyClass other = (MyClass) o;
if (other.firstString != null && this.firstString != null
&& this.firstString.equals(other.firstString) return true;
return false;
}
编辑:您也应该覆盖 hashCode。覆盖 hashCode 时,您应该考虑覆盖 equals 时考虑的对象。因此,如果您基于属性 firstString 测试两个 MyClass 对象是否相等,则应在 hashCode
中包含
firstString
public int hashCode() {
if (firstString == null) return 31;
return firstString.hashCode();
}
编辑2:
调用 indexOf 时 ArrayList 的作用基本上是这样的:
'for (Entry e = header.next; e != header; e = e.next) {
如果(o.equals(e.element))
回报指数;
索引++;
}'
因此,每次调用 indexOf() 时,ArrayList 都会在对象上调用 equals 方法。
因此,假设您有一个如下所示的列表:
MyClass m1 = new MyClass("this is some random string", other params);
MyClass m2 = new MyClass("this is my target string", other params);
MyClass m3 = new MyClass("this is irrelevant", other params);
list.add(m1);
list.add(m2);
list.add(m3);
现在,您想知道包含“这是我的目标字符串”的 MyClass 对象的索引。
所以你调用 indexOf:
list.indexOf(new MyClass("this is my target string"), other params);
并且,根据您的 equals 实现,它将返回 1。