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

后端 未结 8 1691
灰色年华
灰色年华 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:40

    Your problem here is not only how it treats == but autoboxing... When you compare Y and 9 you are comparing two primitives that are equal, in the last two cases you get false simply because that's how equals work. Two objects are equal only if they are of the same kind and have the same value. When you say in "X.equals(y)" you are telling it to do Integer.equals(Short) and looking at the implementation of Integer.equals() it will fail:

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

    Because of autoboxing the last two will result in the same failure as they will both be passed in as Shorts.

    Edit: Forgot one thing... In the case of results.add(X == y); it will unbox X and do (X.intValue() == y) which happens to be true as well as 9 == 9

提交回复
热议问题