Help with ArrayList in Java

Can anyone tell me the difference between these two snippet of code.
A and B are ArrayList< Integer>

This one gets accepted.

for(int i=0;i<A.size();i++){
    for(int j=0;j<B.size();j++){
           int X = A.get(i);
           int Y = B.get(j);
           if(X == Y)
               ans = X;
      }
   }

This one is giving WA

    for(int i=0;i<A.size();i++){
         for(int j=0;j<B.size();j++){
                  if(A.get(i) == B.get(j))
                         ans = A.get(i);
         }
   }

get() method of ArrayList returns ‘Integer’ type in the example. It’s not a primitive type to compare directly. It’s like object comparision. So, it doesn’t compare the values but the memory locations of objects (if objects are same or not).

int a = list.get(i);
Here, it’s getting converted to primitive type ‘int’. So, you can compare values with ‘==’.

3 Likes

Thank you so much, I hope I knew this before would have had a better rank in October Lunchtime:stuck_out_tongue_winking_eye:

Yes. Sometimes, minute things are the one we overlook and takes a lot of time to identify the issue. Been there a lot. We need to keep learning.

1 Like