What exactly does comparing Integers with == do?

前端 未结 7 575
旧时难觅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:03

    Note also that newer versions of Java cache Integers in the -128 to 127 range (256 values), meaning that:

    Integer i1, i2;
    
    i1 = 127;
    i2 = 127;
    System.out.println(i1 == i2);
    
    i1 = 128;
    i2 = 128;
    System.out.println(i1 == i2);
    

    Will print true and false. (see it on ideone)

    Moral: To avoid problems, always use .equals() when comparing two objects.

    You can rely on unboxing when you are using == to compare a wrapped primitive to a primitive (eg: Integer with int), but if you are comparing two Integers with == that will fail for the reasons @dan04 explained.

提交回复
热议问题