ForguesR
ForguesR

Reputation: 3618

Common case for comparing two objects references

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

Answers (3)

J-Alex
J-Alex

Reputation: 7117

  1. Comparing singletons - singleton should has only one instance and could be checked for identity instead of equality.
  2. Comparing enums (enums are singletons)
  3. 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

hoan
hoan

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:

  1. Checking a reference is null.
  2. Comparing two enum values, because there is only one object for each enum constant.
  3. Checking if two references are to the same object.

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

Gerald M&#252;cke
Gerald M&#252;cke

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

Related Questions