eloso
eloso

Reputation: 133

Using Arraylist in Java

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?

Upvotes: 1

Views: 130

Answers (4)

TheLostMind
TheLostMind

Reputation: 36304

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 **  

Upvotes: 0

Jatin Khurana
Jatin Khurana

Reputation: 1175

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.

Upvotes: 0

rgettman
rgettman

Reputation: 178243

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.

Upvotes: 2

chresse
chresse

Reputation: 5805

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

Upvotes: 3

Related Questions