There are cases when checking for instance equality with
== is necessary. For example, that is what you do in the implementation of
equals to check if you are comparing an object to itself (a very important shortcut that also satisfies the reflexivity requirement of
if (other==this) return true;
The other case is when the system guarantees that there will be only one instance that is equal to any object of a particular class (and by necessity that is going to be the instance itself - again, due to reflexivity of
equals). This is another common case illustrated by your code fragment:
if (other.getClass() != this.getClass())
An equality of two
java.lang.Class objects is equivalent to the equality of their references, because for each class that you define there is one, and only one, instance of
A third case where reference equality is desired is serialization: you need to keep track of object instances by tracking their references, even if they are logically equal, in order to be able to produce an isomorphic graph upon deserialization.
EDIT : Inside implementations of
equals the use of
== boils down to increasing performance: comparing an object to itself is a common case, especially when you use objects of the class as keys in a hash table, so it makes sense to optimize it.