What exactly does comparing Integers with == do?

前端 未结 7 576
旧时难觅i
旧时难觅i 2020-12-10 04:22

EDIT: OK, OK, I misread. I\'m not comparing an int to an Integer. Duly noted.

My SCJP book says:

When == is used to compare a primitive to a

7条回答
  •  庸人自扰
    2020-12-10 05:04

    No, I would not think that code print true, and you answered yourself exactly why.

    When == is used to compare a primitive to a wrapper, the wrapper will be unwrapped and the comparison will be primitive to primitive.

    and you then went on to compare two Integer references- that is, it compared the memory address of i1 and i2. You wanted either

    Integer i1 = 1;
    Integer i2 = new Integer(1);
    System.out.println(i1.equals(i2));
    

    Or

    int i1 = 1;
    Integer i2 = new Integer(1);
    System.out.println(i1 == i2);
    

提交回复
热议问题