Reputation: 3618
Beside checking if null (something == null
) when do we use object reference comparisons in Java?
I can't think of any case to use object reference comparisons. For me that seems a little weird for a language abstracting all memory allocations.
Upvotes: 3
Views: 235
Reputation: 7117
In some equals
methods themselves like in (AbstractList
):
public boolean equals(Object o) {
// Checking identity here you can avoid further comparison and improve performance.
if (o == this)
return true;
if (!(o instanceof List))
return false;
ListIterator<E> e1 = listIterator();
ListIterator<?> e2 = ((List<?>) o).listIterator();
while (e1.hasNext() && e2.hasNext()) {
E o1 = e1.next();
Object o2 = e2.next();
if (!(o1==null ? o2==null : o1.equals(o2)))
return false;
}
return !(e1.hasNext() || e2.hasNext());
}
Upvotes: 7
Reputation: 1098
Comparing Object references with ==
is useful when we need to see if two values refer to the same object.
With object references, the use of ==
is generally limited to the following:
In addition, by default, Object#equals()
uses only the ==
operator for comparisons. This method has to be overridden to really be useful:
public boolean equals(Object obj) {
return (this == obj); // Comparing object references by default
}
Upvotes: 0
Reputation: 11132
It's faster than a full equals comparison.
The reasoning is simple, if two objects are the same, they must be equal. Therefore it's often used in equals implementations but also to compare enums as J-Alex already pointed out.
Upvotes: 0