Why are these == but not `equals()`?

后端 未结 8 1705
灰色年华
灰色年华 2020-12-01 07:58

I\'m a bit confused about the way Java treats == and equals() when it comes to int, Integer and other types of numbers.

8条回答
  •  孤街浪徒
    2020-12-01 08:44

    (small) Integer instances are cached, so the invariant x == y is holded for small instances (actually -127 +128, depends on JVM):

    Integer a = 10;
    Integer b = 10;
    
    assert(a == b); // ok, same instance reused
    
    a = 1024;
    b = 1024;
    
    assert(a == b); // fail, not the same instance....
    assert(a.equals(b)); // but same _value_
    

    EDIT

    4) and 5) yield false because equals check types: X is an Integer whereas Y is a Short. This is the java.lang.Integer#equals method:

    public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
    
        return false;
    }
    

提交回复
热议问题