I have a problem using Arraylists in java my code looks something like this:
List<Integer> numbers1 = new ArrayList<>();
List<Integer> numbers2 = new ArrayList<>();
boolean bcompare;
I add to the lists the same numbers, but when i try to compare the numbers of the index 0 of the lists like this the result of the boolean is false when it should be true:
bcompare = numbers1.get(0)==numbers2.get(0);
bcompare is false
But here is the thing when I use some temp variables and then compare them it gives me what i expected, a true value on bcompare:
int a=numbers1.get(0);
int b=numbers2.get(0);
bcompare = a==b;
bcompare is true
What am I doing wrong here?
4 Answers 4
It is cause you use the wrapper classes Integer. So an == compares the "references".
Use the equals() method instead to compare values of objects:
bcompare = numbers1.get(0).equals(numbers2.get(0));
The second comparison is true, because a int is a primitive type and contains only the value.
Have a look at http://mindprod.com/jgloss/intvsinteger.html for more details about the difference between int and Integer
Comments
When compare the results of get, you are comparing Integers. Using ==, this will compare the two object references to see if they are the same reference. With the exception of Integer caching, this will be false.
When you first assign the numbers to int, Java unboxes the Integer to int, so that == can compare the primitive values directly. This works as you intended.
Use the last code which uses int values.
3 Comments
numbers1 and numbers2 and it returns true. Am I missing something?ArrayList<Integer> list = new ArrayList<Integer>(); ArrayList<Integer> list2 = new ArrayList<Integer>();list.add(1); list2.add(1); boolean bcompare = list.get(0)==list2.get(0); System.out.println(bcompare);Integer question. The values at least in the range -128 to 127 are cached, so that the Integers for 1 in both lists are actually the same.return type of get() method is Object so when you are comparing like this
bcompare = numbers1.get(0).equals(numbers2.get(0));
It compares the reference of two different object so giving false.
either use equals() method or downcast it to the Integer class.
Using equals() method is good idea out of these both.
Comments
As,others have already said bcompare = numbers1.get(0)==numbers2.get(0); compares references of 2 Integer objects (which are not same, so, it will be false). int a=numbers1.get(0); extracts the int value from Integers ( by calling integer.intValue() implicitly) and compares them so, a==b; will be true.
Byte code :
public static void main(java.lang.String[]);
*** some code here***
30: if_acmpne 37 // byte code instruction to compare references
49: invokevirtual #27 // Method java/lang/Integer.intValue:()I
*** some other code here **
ArrayListcontain any elements? Which ones?