Why is object.equals (new Integer (1)) equal to true?

I am trying to understand this koan:

@Koan
public void equalsMethodCanBeChangedBySubclassesToTestsIfTwoObjectsAreEqual() {
    Object object = new Integer(1);
    assertEquals(object.equals(object), true);
    assertEquals(object.equals(new Integer(1)), __);
    // Note: This means that for the class 'Object' there is no difference between 'equal' and 'same'
    // but for the class 'Integer' there is difference - see below
}

As far as I understand, since it objectis an instance of the class object, the method has .equals()not been overwritten and therefore checks the equality of the object.

If new Integer(1)creating a new instance, it must be a separate object object. Following my example, the correct answer should be false, but only truemakes this passage. Where is the error in my logic?

Edit: I understand that integers from -128 to 127 are cached. If my understanding of the object is objectcorrect (as indicated above), then it does not matter.

+4
source share
5 answers

equals , int int Integer, , true. , Integer equals , , , object Integer.

- , - equals .

true:

    print((new Integer(1).equals(1)));
    print((new Integer(1).equals(new Integer(1))));
    print((((Integer) 1).equals(new Integer(1))));
    print(((Integer) 1).equals(1));

, [-128,127]. true:

    1 == ((Integer) 1)
    ((Integer) (-128)) == ((Integer) (-128)) // in autoboxing range
    ((Integer) (+127)) == ((Integer) (+127)) // same

    ((Integer) (-200)) != ((Integer) (-200)) // not autoboxing
    ((Integer) (+200)) != ((Integer) (+200)) // same

    ((Integer) (-128)) != (new Integer(-128)) // explicit new instance, so no autoboxing
    ((Integer) (+127)) != (new Integer(+127)) // same
+9

equals Integer. Integer ( Integer Integer ). ( ) ().

, - ( ):

 Comparable<Integer> a = 1;
 Serializable b = 1;
 assertTrue(a.equals(b));

, "" . , , ( , , ).

+4

, object object, .equals() .

. object object, Integer. equals() Integer, .

, , "" . , Integer , Integer, object.

+4

Dynamic Method Dispatch?

, , .

Therefore, although you use Object object = new Integer(1);, calling equals on an object always calls Integer.equals().

And it Integer.equals()checks the equality of integers, not necessarily the same reference.

+2
source

If the new Integer (1) creates a new instance, it must be a separate object for the object.

What are you mistaken. A new instance Integer(1)will be falsefor ==, but truefor equals.

+1
source

All Articles