[Java] indexOf使用等于吗?

时间:2016-05-24 13:37:08

标签: java override equals indexof

我想知道如何实现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。 (我检查了我要找的元素)

我完全错了吗?

2 个答案:

答案 0 :(得分:6)

当比较的对象不是同一类型时,

equals永远不会返回true(在您的情况下CustomObject&#39; s equals应始终在{{1}时返回false }不是o)的实例。

CustomObject的实施恰好在您通过时使用indexOf String代替equals CustomObject一个equalsString&#39; s String在向其传递非equals的对象时返回false。

此外,在比较字符串时不要使用String

您应该将==的实例传递给CustomObject

indexOf

(或customObjects.indexOf(new CustomObject("name")) 的构造函数看起来像什么)

您的CustomObject方法应如下所示:

equals

答案 1 :(得分:0)

customObjects.indexOf(new String("name")) 

这就是你做错了。您正在寻找String对象列表中CustomObject的索引。

来自java docs:

 /**
     * 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);