0

Possible Duplicate:
Why is == true for some Integer objects?

I have code fragment

Integer i1 = new Integer(a);
Integer i2 = new Integer(b);
if (i1 == i2)
{
// ...
}

When 'a' and 'b' are small numbers (e.g. 0-20) then i1 == i2 return true.
But when 'a' and 'b' are great then i1 == i2 rerun false!
I don't understand, how can it be

Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

1

Read more about pool of integer values.
If 'a' and 'b' are between -127 and 128 then i1 == i2 return true
else i1 == i2 return false
Better use method .equals comparison.
if (i1.equals(i2))
{ }

Ilya
  • 29,135
  • 19
  • 110
  • 158
0

Keep in mind you're using an Object and not a datatype. Integer has an equals method which is defined as:

Compares this object to the specified object. The result is true if and only if the argument is not null and is an Integer object that contains the same int value as this object.

You'll typically want to use the equals method for checking equality of Objects.

The quote is from: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#equals(java.lang.Object)

OnResolve
  • 4,016
  • 3
  • 28
  • 50