Q: What's up with integers not being equal to one another? The following code prints "true, true, false, true". Shouldn't it be "true, true, true, true"?
Integer i = 127;
Integer j = 127;
System.out.println(i == j);
System.out.println(i.equals(j));
Integer i1 = 128;
Integer j1 = 128;
System.out.println(i1 == j1);
System.out.println(i1.equals(j1));
The key to understanding this is that the JVM uses a process called "boxing" (or "auto-boxing") when converting an int (like 127) to an Integer object. This involves calling the Integer.valueOf(127) method. The JavaDoc:java.lang.Integer#valueOf(int) says: "Returns a Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values." What that means is that the valueOf() method has a cache of Integer objects, and if the primitive being boxed is in that range, the cached object is returned. It just so happens that 127 is in that range, but 128 is not. So i and j are the same object, while i1 and j1 are not.
--------------------------------------------------------------------------------
from:[url]http://www.coderanch.com/how-to/java/Java-FAQ[/url]
Integer i = 127;
Integer j = 127;
System.out.println(i == j);
System.out.println(i.equals(j));
Integer i1 = 128;
Integer j1 = 128;
System.out.println(i1 == j1);
System.out.println(i1.equals(j1));
The key to understanding this is that the JVM uses a process called "boxing" (or "auto-boxing") when converting an int (like 127) to an Integer object. This involves calling the Integer.valueOf(127) method. The JavaDoc:java.lang.Integer#valueOf(int) says: "Returns a Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values." What that means is that the valueOf() method has a cache of Integer objects, and if the primitive being boxed is in that range, the cached object is returned. It just so happens that 127 is in that range, but 128 is not. So i and j are the same object, while i1 and j1 are not.
--------------------------------------------------------------------------------
from:[url]http://www.coderanch.com/how-to/java/Java-FAQ[/url]