Java ArrayList IndexOf – 查找对象索引
让我们说我上课了
public class Data{ public int k; public int l; public Data(int k, int l){ this.k = k; this.l = l; } public boolean equals(Date m){ if(this.k == mk && this.l = ml) return true; return false; } }
我向ArrayList添加了一些Data对象:
ArrayList holder = new ArrayList; Data one = new Data(0,0); Data two = new Data(0,4); Data three = new Data(0,5);
为什么indexOf找不到这个?:
holder.indexOf(new Data(0,4)); //returns -1
indexOf是否比自己遍历整个数组列表更好? 或者我错过了什么。
indexOf()
方法确实遍历整个列表。 这是Java 7源代码的摘录:
public int indexOf(Object o) { if (o == null) { for (int i = 0; i < size; i++) if (elementData[i]==null) return i; } else { for (int i = 0; i < size; i++) if (o.equals(elementData[i])) return i; } return -1; }
让Java通过它比自己写它更好。 只需确保您的equals
方法足以找到您想要的对象。 您还需要覆盖hashCode()
。
我不会写出你的equals
方法,但至少我建议你:
- 检查是否为空
- 测试您比较的实例是否相同
- 你不需要做
if(boolean_expr) { return true; }
if(boolean_expr) { return true; }
; 只返回布尔表达式。 - 确保你实际上覆盖了你的
equals
方法 - 签名需要一个Object
参数,而不是Date
。
你的equals
方法的签名是错误的。 你没有覆盖Object
的equals
,只是重载它。
要覆盖Object
中equals
方法的行为,您的签名必须与Object
中的签名完全匹配。 尝试这个:
public boolean equals(Object o) { if(!(o instanceof Data)) return false; Data other = (Data) o; return (this.k == other.k && this.l == other.l); }
此外,正如其他人所建议的那样,最好覆盖hashCode
方法,以使对象在基于地图的集合中正常工作。
Makoto的答案是对的。 同样我会说。 但是你的代码中有一些错误。
- 你写了“public boolean equals(Date m){”。 我想,你的意思是数据而不是日期。
- 你写了“if(this.k == mk && this.l = ml)”。 if查询中的第二个条件必须是“==”。
对于你的问题:Makoto的答案是一个解决方案。 我的解决方案是使用eclipse的帮助来自动生成hashcode和equals方法。 喜欢这个:
public class Data { // your class code here public int hashCode() { final int prime = 31; int result = 1; result = prime * result + k; result = prime * result + l; return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Data)) { return false; } Data other = (Data) obj; if (k != other.k) { return false; } if (l != other.l) { return false; } return true; } }
按照惯例,您希望在覆盖equals时也覆盖哈希码
您很可能会发现indexOf使用hashcode方法匹配对象而不是equals
如果你使用eclise来编辑代码 – eclipse将从“source”菜单中为你生成一个好的equals和hashcode方法。