[Java] indexOf使用等于吗?

use*_*621 3 java overriding 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我虽然这会避免我覆盖indexOf方法,但似乎我完全错了.当我尝试

ArrayList<CustomObject> customObjects = new ArrayList<CustomObject>
... insert customobject into the arraylist ...
customObjects.indexOf(new String("name")) 
Run Code Online (Sandbox Code Playgroud)

indexOf返回false但它应该返回true.(我检查了我要找的元素存在)

我完全错了吗?

Era*_*ran 6

equals当比较的对象都是同一类型的不应该永远不会返回true(在你的情况CustomObjectequals应该永远当返回false o不是一个实例CustomObject).

实施indexOf恰巧使用Stringequals,而不是你CustomObjectequals,当你传递String给它,和Stringequals,当你传递给它的对象是不是返回false String.

另外,不要==在字符串的比较中使用.

你应该通过实例CustomObjectindexOf:

customObjects.indexOf(new CustomObject("name")) 
Run Code Online (Sandbox Code Playgroud)

(或任何CustomObject看起来像的构造函数)

您的equals方法应如下所示:

public boolean equals(Object o) {
    if(!(o instanceof CityLoader))
        return false;
    CityLoader other = (CityLoader)o;
    return other.name.equals(this.name);
}
Run Code Online (Sandbox Code Playgroud)