- Integer i=45; Integer k=45;
System.out.println("k.hashcode= "+k.hashCode());
System.out.println(i==k);
System.out.println(i.equals(k));
Out Put:
i.hashcode= 45
k.hashcode= 45
true
true
Great, it seems work fine! now change the value of i=k=201.
Integer i=201;
Integer k=201;
System.out.println("i.hashcode= "+i.hashCode());
System.out.println("k.hashcode= "+k.hashCode());
System.out.println(i==k);
System.out.println(i.equals(k));
OutPut:
i.hashcode= 201
k.hashcode= 201
false // System.out.println(i==k);
true
The reason behind this is the IntegerCache, a private static inner class in Integer class. This was feature was introduced in java 1.5 for performance improvement.
An implementation of flyweight
design pattern . A flyweight is an object that minimises memory use by sharing
as much data as possible with other similar objects.
so, integer cache
help auto boxing between the range [-128 to 127].
Now how auto boxing happen?
When we do the following in java 1.5 onwards
Integer K=23;
program flow goes to following method of Integer class
public static Integer valueOf(int i) {
if (i >=
IntegerCache.low && i <= IntegerCache.high)
return
IntegerCache.cache[i + (-IntegerCache.low)];
return new
Integer(i);
}
so , above code checks if the int i lies between [-128 to
127] then the object from integer cache else it creates a new integer object
using new operator.
That’s why checking equality using == operator only holds
between the range -128 to 127.
one exception to above rule; if we create object using new operator
and even if the integer lies between [-128 to 127] equality using == operator will
not hold true when values are same.
Caching also supported by java.lang.Long and java.lang.Character
in Character class cache array hold 128 objects(The ASCII table) unlike Integer and Long.
Caching also supported by java.lang.Long and java.lang.Character
in Character class cache array hold 128 objects(The ASCII table) unlike Integer and Long.
Comments
Post a Comment