1、自动的装箱与拆箱机制:
Java为每个基本的数据类型提供类包装类,对应关系如下:
从java5引入了自动的拆箱与装箱的机制,使基本的数据类型与包装类能相互转换;
public class AutoUnboxingTest {
public static void main(String[] args) {
Integer a=new Integer(3);
Integer b=3;
int c=3;
System.out.println("a==b:"+(a==b));//两个引用类型没有引用一个对象 结果为:false
System.out.println("a==c:"+(a==c));//自动的拆箱操作 ,转成int进行比较 结果为true
}
}
结果:
a==b:false
a==c:true
2、IntegerCache
public class IntegerCacheTest {
public static void main(String[] args) {
Integer f1=100,f2=100,f3=150,f4=150;
System.out.println(f1==f2);
System.out.println(f3==f4);
}
}
结果:
true
false
分析:
1、f1,f2,f30,f4都是Integer类型,都是引用类型
2、==比较的就是引用的内存地址
3、当给一个Integer赋值一个int值时,就是装箱操作时就会调用valueOf方法,看一下这个方法:
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
IntegerCache是Integer 的内部类;
源码如下:
/**
* Cache to support the object identity semantics of autoboxing for values between
* -128 and 127 (inclusive) as required by JLS.
*
* The cache is initialized on first usage. The size of the cache
* may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
* During VM initialization, java.lang.Integer.IntegerCache.high property
* may be set and saved in the private system properties in the
* sun.misc.VM class.
*/
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
总结:
1、如果整数值在-128-127之间的值是不会new 新的Integer的对象的,而是直接的引用常量池中的Integer对象;