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?
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++;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With