My code is here:
ArrayList<Integer> list1 = new ArrayList<>();
list1.add(4444);
list1.add(4444);
System.out.println(list1.get(0) == list1.get(1));
It print out as false. What is the reason? normally 4444 == 4444 should be true. Thank you.
My code is here:
ArrayList<Integer> list1 = new ArrayList<>();
list1.add(4444);
list1.add(4444);
System.out.println(list1.get(0) == list1.get(1));
It print out as false. What is the reason? normally 4444 == 4444 should be true. Thank you.
List
(and other Collection
subclasses) store objects, not primitives.
In Java 4 and before, list1.add(4444);
would have been a compilation error.
Since Java 5, there is autoboxing: if you pass a primitive in a place that expects an instance of an object, the JVM automatically converts it to its wrapper value. So you end with your code working like list1.add(Integer.valueOf(4444))
.
When you do the get
, you are comparing not two primitives but two objects, so you must use .equals()
to compare them.
Funny nitpick, because of how Integer.valueOf
, if you had used 111
(or anything in the -128 to 127 range) in your example, your comparation would have returned true
, since for those values the instances of integer are in a cache and Integer.valueOf
returns always the same instance, not a new one.