views:

234

answers:

2

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?

+12  A: 

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++;
    }
}
David M
Both `e` and `o` can be `null` (at least in some collections).
Joachim Sauer
Yes, but that's already been catered for by the time you reach the loop. That's why I say `o` is known not to be null.
David M
Have edited the answer to make this clearer.
David M
I understood the question to be about the definition of the methods and not so much about the implementation, but looking back at it it could equally well be the other way around ...
Joachim Sauer
The definition also caters for `o` being null before it gets to `.equals`....
David M
David should have posted the full code of `indexOf`. There you see, that `o` can not be null in that part of the function.
ablaeul
I now have done (or at least enough to make that clearer).
David M
A: 

The difference between using x.equals(y) and y.equals(x) is the following:

If x is null, y.equals(x) would simply return false whyle x.equals(y) would result in a NullPointerException.

aioobe
The way the methods are defined in the Javadoc ensures that `equals()` is never called with a `null` argument and is never called on a `null` reference.
Joachim Sauer
How can the documentation ensure that I wont call `equals()` with a `null` argument?
aioobe