Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Integer values in Java, strange behavior

Tags:

java

Walk with me ..

Integer x = 23; Integer y = 23;  if (x == y)     System.out.println("what else");      // All is well as expected else     System.out.println("..."); 

While

Integer x = someObject.getIndex(); Integer y = someOtherObject.getSomeOtherIndex();  if (x == y)     System.out.println("what else");   else     System.out.println("...");        // Prints this  

Hmm ... I try casting to int

int x = someObject.getIndex(); int y = someOtherObject.getSomeOtherIndex()  if (x == y)            System.out.println("what else");   // works fine else     System.out.println("...");   

Are they both Integers?

System.out.println(x.getClass().getName());              // java.lang.Integer System.out.println(y.getClass().getName());              // java.lang.Integer System.out.println(someObject.getIndex());               // java.lang.Integer System.out.println(someOtherObject.getSomeOtherIndex()); // java.lang.Integer 

What do you guys think? What would explain something like this?

like image 307
James Raitsev Avatar asked Apr 03 '12 21:04

James Raitsev


People also ask

How can I properly compare two integers in Java?

Syntax : public static int compare(int x, int y) Parameter : x : the first int to compare y : the second int to compare Return : This method returns the value zero if (x==y), if (x < y) then it returns a value less than zero and if (x > y) then it returns a value greater than zero. Example :To show working of java.

How do you compare two integer values?

compare(int x, int y) compare() compares two int values numerically and returns an integer value. If x>y then the method returns an int value greater than zero. If x=y then the method returns zero.

Can I use == to compare integer in Java?

To compare integer values in Java, we can use either the equals() method or == (equals operator). Both are used to compare two values, but the == operator checks reference equality of two integer objects, whereas the equal() method checks the integer values only (primitive and non-primitive).

Can you compare integer and int?

In Java, int is a primitive data type while Integer is a Wrapper class.


1 Answers

You're comparing Integer values, which are references. You're coming up with those references via autoboxing. For some values (guaranteed for -128 to 127) the JRE maintains a cache of Integer objects. For higher values, it doesn't. From section 5.1.7 of the JLS:

If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

Ideally, boxing a given primitive value p, would always yield an identical reference. In practice, this may not be feasible using existing implementation techniques. The rules above are a pragmatic compromise. The final clause above requires that certain common values always be boxed into indistinguishable objects. The implementation may cache these, lazily or eagerly. For other values, this formulation disallows any assumptions about the identity of the boxed values on the programmer's part. This would allow (but not require) sharing of some or all of these references.

This ensures that in most common cases, the behavior will be the desired one, without imposing an undue performance penalty, especially on small devices. Less memory-limited implementations might, for example, cache all char and short values, as well as int and long values in the range of -32K to +32K.

Moral: don't compare Integer references when you're interested in the underlying int values. Use .equals() or get the int values first.

like image 76
Jon Skeet Avatar answered Oct 20 '22 19:10

Jon Skeet