Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do contains()/indexOf() in Java collections use o.equals(e) and not e.equals(o)?

Why are the methods contains() and indexOf() in the Java collections framework defined using o.equals(e) and not e.equals(o) (where o is the argument of the methods and e is the element in the collection)?

Anyone know the reasons of that?

like image 988
Fernando Avatar asked Oct 23 '25 15:10

Fernando


1 Answers

Because o is known not be null, but e isn't necessarily. Take this example from the code for LinkedList:

for (Entry e = header.next; e != header; e = e.next) {
    if (o.equals(e.element))
        return index;
    index++;
}

In this example, doing it this way round avoids the need to protect against e.element being null for every item in the collection. Here's the full code that takes account of o being null:

if (o == null) {
    for (Entry e = header.next; e != header; e = e.next) {
        if (e.element == null)
            return index;
        index++;
    }
} else {
    for (Entry e = header.next; e != header; e = e.next) {
        if (o.equals(e.element))
            return index;
        index++;
    }
}
like image 112
David M Avatar answered Oct 25 '25 05:10

David M