ArrayList and foreach question
Hi everyone,
I need help understanding the code below. The problem I am facing is that when I add two numbers bigger than 127 into the array, the print statement only prints out one value otherwise it prints out two values. To my understanding it should always print out the two values in the array. Whats going on?
Many thanks
Code :
import java.util.ArrayList;
import java.util.Random;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> array = new ArrayList<Integer>();
array.add(127);
array.add(127);
for (Integer integer : array) {
if(integer == array.get(0)){
System.out.println(integer);
}
}
}
}
Re: ArrayList and foreach question
The key here is that you're using == to compare two reference variables, and if you're familiar with why you shouldn't do this with Strings, you should understand what is happening here. The JVM uses a pool or cache of Integer objects for numbers from -126 to 127 so that new Integer(25) will == another new Integer(25) because they will refer to the exact same object. The same is not true for numbers greater than 128. The solution is the same as for String: use the equals(...) method.
Re: ArrayList and foreach question
Thanks curmudgeon,
I understand that I need to use equals(....) for the code to work. What I probably need to read up more on is why it works for numbers from -126 to 127. Again Thanks.
Re: ArrayList and foreach question
I stand corrected from my first post. This is mainly occurring here because you're using boxing to create your Integer object from int objects. Java will get Integers from -126 to 127 from an IntegerCache. I believe that this is all well described in the JLS, the Java Language Specification in the boxing-unboxing section.