Java ArrayList IndexOf - 查找对象索引 [英] Java ArrayList IndexOf - Finding Object Index
问题描述
假设我有一堂课
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 == m.k && this.l = m.l)
return true;
return false;
}
}
然后我将一些 Data 对象添加到 ArrayList 中:
And I add a few Data objects to a ArrayList:
ArrayList<Data> holder = new ArrayList<Data>;
Data one = new Data(0,0);
Data two = new Data(0,4);
Data three = new Data(0,5);
为什么 indexOf 找不到这个?:
Why does indexOf not find this?:
holder.indexOf(new Data(0,4)); //returns -1
indexOf 是否比自己遍历整个数组列表更好?或者我错过了什么.
Is indexOf any better than going through the whole array list myself? Or am I missing something.
推荐答案
indexOf()
方法确实遍历整个列表.以下是 Java 7 源代码的摘录:
The indexOf()
method does go through the entire list. Here's an excerpt from Java 7 source code:
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()
.
It'd be better to let Java go through it than write it yourself. Just make sure that your equals
method is sufficient at finding the object you want. You'll also want to override hashCode()
as well.
我不会写出您的 equals
方法,但我建议您至少:
I won't write your equals
method out, but I would recommend that you at least:
- 检查是否为空
- 测试您比较的实例是否相同
- 你不需要做
if(boolean_expr) { return true;}
;只需返回布尔表达式. - 确保您实际上覆盖了
equals
方法 - 该方法的签名需要Object
参数,而不是Date
.
- Check for null
- Test if the instances you're comparing are the same
- You don't need to do
if(boolean_expr) { return true; }
; just return the boolean expression. - Make sure you're actually overriding your
equals
method - the signature of that requires anObject
parameter, notDate
.
这篇关于Java ArrayList IndexOf - 查找对象索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!