[英][Java]Does indexOf use equals?
我想知道如何实现ArrayList的方法indexOf。 实际上我已经覆盖了equals方法,如下所示:
public class CustomObject {
@Override
public boolean equals(Object o) {
if(o instanceof CityLoader)
return ((CityLoader)o).getName() == this.name;
else if (o instanceof String)
return this.name.equals((String)o);
return false;
}
}
我虽然这会避免我覆盖indexOf方法,但似乎我完全错了。 当我尝试
ArrayList<CustomObject> customObjects = new ArrayList<CustomObject>
... insert customobject into the arraylist ...
customObjects.indexOf(new String("name"))
indexOf返回false但它应该返回true。 (我检查了我要找的元素存在)
我完全错了吗?
equals
当比较的对象都是同一类型的不应该永远不会返回true(在你的情况CustomObject
的equals
应该始终返回false时o
不是一个实例CustomObject
)。
当你向它传递一个String
时, indexOf
的实现碰巧使用String
的equals
而不是你的CustomObject
的equals
,而当你传递一个不是String
的对象时, String
的equals
返回false。
另外,在比较字符串时不要使用==
。
您应该将CustomObject
的实例CustomObject
给indexOf
:
customObjects.indexOf(new CustomObject("name"))
(或者任何CustomObject
的构造CustomObject
看起来像)
你的equals
方法应如下所示:
public boolean equals(Object o) {
if(!(o instanceof CityLoader))
return false;
CityLoader other = (CityLoader)o;
return other.name.equals(this.name);
}
customObjects.indexOf(new String("name"))
这就是你做错了。 您正在查找CustomObject
对象列表中的String
索引。
来自java文档:
/** * Returns the index of the first occurrence of the specified element * in this list, or -1 if this list does not contain the element. * More formally, returns the lowest index <tt>i</tt> such that * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, * or -1 if there is no such index. * * @param o element to search for * @return the index of the first occurrence of the specified element in * this list, or -1 if this list does not contain the element * @throws ClassCastException if the type of the specified element * is incompatible with this list * (<a href="Collection.html#optional-restrictions">optional</a>) * @throws NullPointerException if the specified element is null and this * list does not permit null elements * (<a href="Collection.html#optional-restrictions">optional</a>) */ int indexOf(Object o);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.