Comparing Wrappers other than String

public class A {
public static void main(String[] args) {
Integer i1=100; Integer i2=100;
System.out.println(i1==i2);//true
Integer i3=200; Integer i4=200;
System.out.println(i3==i4);//false -- why ??
}
}

Reason:

The Integer wrapper class interns the objects from -127 to +128. So all Integers with a value less than 128 are the same as they are interned. The values greater than 128 are not the same because they are not interned.

The JVM will create a cache of objects(something similar to the string constant pool) for the above range and assigns the same object(if it already exists) when ever a new object with the same value is created. So in your case, the two Integers for 100 will use the same object and the ones for 200 won’t be the same.

you assign a integral literal to a Integer reference, it will invoke the Integer.valueOf(..) method.

This method uses the famous Fly-weigh pattern. That is that the -128~127 integers are cached. So the “i1==i2” will be true. Of course, you can change the cache range by setting IntegerCache.low or IntegerCache.high which are static variables.

Always compare wrapper classes with equals(e).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: