Compare Integer with ==

History

I saw something unpleasant when I woke up. https://twitter.com/EclipseJavaIDE/status/1043084678339719168

Set<Short> set = new HashSet<>();
for (short i = 0; i < 10; i++) {
    set.add(i);
    set.remove(i - 1);
}
System.out.println(set.size());

Choose your choice.

  1. Exception with remove → out of the question 2.0 → I don't know in the first place 3.1 → Expected incorrect answer
  2. 10 → Correct answer

The reason is that i-1 will change from int type to Integer type, so it will not match the elements of Set held in Short type. .. ..

Basic confirmation

System.out.println(1 == new Integer(1));
System.out.println(1 == Integer.valueOf(1));
System.out.println(new Integer(1) == new Integer(1));
System.out.println(Integer.valueOf(1) == Integer.valueOf(1));
System.out.println(new Integer(1) == Integer.valueOf(1));

The result is as follows. true true false true false

Check if you know

System.out.println(Integer.valueOf(-129) == Integer.valueOf(-129));
System.out.println(Integer.valueOf(-128) == Integer.valueOf(-128));
System.out.println(Integer.valueOf(127) == Integer.valueOf(127));
System.out.println(Integer.valueOf(128) == Integer.valueOf(128));

The result is as follows. false true true false

It's for efficiency. The 127 and 128 thresholds should have changed in the system properties.

Also basic confirmation

System.out.println(1 + 1 == new Integer(1) + 1);
System.out.println(new Integer(1 + 1) == new Integer(1) + 1);

The result is as follows. true true

The right side will be an int type.

Based on

List<Integer> list = new ArrayList<>();
list.add(1);
list.add(1);
list.add(128);
list.add(128);
System.out.println(list.get(0) == list.get(1));
System.out.println(list.get(0) == list.get(1) + 0);
System.out.println(list.get(2) == list.get(3));
System.out.println(list.get(2) == list.get(3) + 0);

The result is as follows. true true false true

If you take +0, it's nice that the result changes depending on the range of values.

Probably it doesn't work well because I understand the specifications and it doesn't +0, but it should be like this. In addition, I don't know what it is, but I said that I needed +0, and even if I did a regression test, I didn't notice that the behavior changed when I did it in about 1, 2 or 3, and the bomb was set. ..

Ahaha.

Recommended Posts

Compare Integer with ==
If you dare to compare Integer with "==" ...
Integer check method with ruby
Compare Java 8 Optional with Swift
Integer memo
Overload method with Int and Integer arguments
[Java] How to compare with equals method