 # Getting wrong output with 500,500,500 and right or 5,5,5

``````    int n=a.size();
int count=0;
int i=0;
while(i<n){
**while((i+1)<a.size() && a.get(i)==a.get(i+1))**{
count++;
int j=i+1;
a.remove(j);
}
i++;
}
System.out.println(n-count);``````

Yes! Works for all cases but for 5000,5000,5000 or 5001 5001 5001…very unusual behaviour.
But again works for 1,1,1. Strange!!

``````public class Solution {
public int removeDuplicates(ArrayList<Integer> a) {
if(a.size()==0)
return 0 ;
int j=1;
for(int i=1;i<a.size();i++)
{

if(a.get(i)==a.get(i-1))
{
continue;
}
else
{
a.set(j,a.get(i));
j++;
}
}
return j;

}
``````

}

Even I am facing the same problem, can anyone help.

Even i am facing the same problem. Tried in another IDE as well…STRANGE !!!

use a.get(i).equals(a.get(i+1)

Yes, this occurs because the JVM caches the value of integers from -128 to 127 while for integers out of this range, it creates a new reference and stores that. So when you do “==”, in the first case, actual values are compared while in the second case, reference to the integers are compared. For more clear detail, look at the second answer of https://stackoverflow.com/questions/3130311/weird-integer-boxing-in-java

I also got confused for the same test case.

Here the catch is, list.get(i) returns Integer wrapper object so either cast it to primitive int
OR
use compareTo()/equals() method of wrapper Integer

also intValue() can be used.

a.get(i).intValue() == a.get(i+1).intValue()