Comparision error


if(a.get(j)==a.get(j-1))//for this question this didn’t worked even when ArrayList was of Integer

if((int)a.get(j)==(int)a.get(j-1))//but when i changed to this it worked

Can anyone please explain this?


A.get(i) will give you the object not value. That’s why, you are comparing two different objects reference instead you should compare object value


I don’t think that true. These types of camparisons have worked perfectly in other questions, without typecasting them. The compiler here acts differently than other problems.


No its right, in Java smaller Integer values (<128) are cached, so you can use == to compare
But in case of bigger values you cant use ==. You have to use object comparison( equals() ) or type cast to int