比较两个对象引用的常见情况

For*_*esR 3 java comparison object object-reference

除了检查null(something == null)我们何时在Java中使用对象引用比较?

我想不出任何使用对象引用比较的情况.对于我来说,抽象所有内存分配的语言似乎有点奇怪.

J-A*_*lex 7

  1. 比较单例 - 单例应该只有一个实例,可以检查身份而不是相等.
  2. 比较枚举(枚举是单身)
  3. 在某些equals方法本身就像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());
    }
    
    Run Code Online (Sandbox Code Playgroud)