Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 656
ForguesR Avatar asked May 04 '26 18:05

ForguesR


1 Answers

  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());
    }
    
like image 138
J-Alex Avatar answered May 06 '26 07:05

J-Alex