Comparision error


#1

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?


#2

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


#3

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.


#4

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