I was working on Java ArrayList of Integers. However, I found that after certain negative int value; Collection of Type <Integer>
start behaving weirdly with ==
operator.
Please see the code below:
import java.util.*;
public class JavaWeirdness
{
public static void main(String[] args)
{
for(int i=0;i>=-200;i--)
{
ArrayList<Integer> list = new ArrayList<>();
list.add(i);
list.add(i);
System.out.println("For i = "+ i);
System.out.println((list.get(0) == list.get(1)));
}
}
}
When i <= -129
then it prints false
for every value.
Thus it puzzled me; Is it because of Refrence Type Integer
instead of primitive int
?
As If we change:
list.get(0) == list.get(1);
To:
(int) list.get(0) == (int) list.get(1));
Everything starts working fine.
OR
Even if we use .equals()
instead of ==
it works fine.
like:
list.get(0).equals(list.get(1));
BUT
My question here is: WHY? Is it happening in first place?
is it because of auto-boxing
and unboxing
?
Or
is it because of buffer
issues? If you closely observe it is -((2^7)+1)
and onwards.
Or
is it because of collections issues?
Or
is it a bug? (I don't think that'll be the case)
Or
is it because of some IEEE number standards?
Or
anything else?
This is kinda weird; However, I hope experts here will help me out.
PS. please don't ask why I've written this weird code (Let us say I was just testing something :P :D)