Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[Java]Does indexOf use equals?

I was wondering how the method indexOf of an ArrayList is implemented. In fact I have override the equals method like this:

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;
    }
}

I though this will avoid me to override also the indexOf method but it seems I am totally wrong. When I try

ArrayList<CustomObject> customObjects = new ArrayList<CustomObject>
... insert customobject into the arraylist ...
customObjects.indexOf(new String("name")) 

indexOf return false but it should return true. (I checked the element I am looking for exists)

Am I totally wrong?

like image 245
user1315621 Avatar asked May 24 '16 13:05

user1315621


1 Answers

equals should never return true when the compared objects are not of the same type (in your case CustomObject's equals should always return false when o is not an instance of CustomObject).

The implementation of indexOf happens to use String's equals instead of your CustomObject's equals when you pass a String to it, and String's equals returns false when you pass to it a object that is not a String.

In addition, don't use == in comparison of Strings.

You should pass an instance of CustomObject to indexOf :

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

(or whatever the constructor of CustomObject looks like)

Your equals method should look like this :

public boolean equals(Object o) {
    if(!(o instanceof CityLoader))
        return false;
    CityLoader other = (CityLoader)o;
    return other.name.equals(this.name);
}
like image 115
Eran Avatar answered Oct 14 '22 18:10

Eran