繁体   English   中英

[Java] indexOf使用等于吗?

[英][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(在你的情况CustomObjectequals应该始终返回false时o不是一个实例CustomObject )。

当你向它传递一个String时, indexOf的实现碰巧使用Stringequals而不是你的CustomObjectequals ,而当你传递一个不是String的对象时, Stringequals返回false。

另外,在比较字符串时不要使用==

您应该将CustomObject的实例CustomObjectindexOf

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&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM