3

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.

DAIRAV
  • 723
  • 1
  • 9
  • 31
ForguesR
  • 3,558
  • 1
  • 17
  • 39

3 Answers3

7
  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());
    }
    
J-Alex
  • 6,881
  • 10
  • 46
  • 64
  • I realize that code is [from java.util.AbstractSet](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/AbstractSet.java#AbstractSet.equals%28java.lang.Object%29), but it’s still a poor example due to that try/catch part. No one should be catching NullPointerException. Or ClassCastException, for that matter. – VGR Apr 20 '18 at 15:27
  • Agree, found a better implementation – J-Alex Apr 20 '18 at 15:45
  • So in short we can say that `==` merely provides a way of optimizing `equals` comparison. – ForguesR Apr 20 '18 at 17:48
0

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.

Gerald Mücke
  • 10,724
  • 2
  • 50
  • 67
0

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
}
hoan
  • 1,058
  • 8
  • 13