byte -- Byte
short -- Short ? ? ? ? ?
int ?-- ?Integer
long -- Long
float -- Float
Double -- Double
boolean -- Boolean
char -- Character? ?
?
? ? ? ? ? 从JDK1.5之后java引入了自动装箱与自动拆箱技术。
? ? ? ? ? 一般我们产生一个对象都是通过new的形式,而包装类型的自动装箱则是这样:
?
? ? ? ? ?不必感到诧异,其实底层在编译阶段就把上述代码改成:
? ?---------------------------------------------------------------------------------------------------
? ? ? ? ?拆箱机制:
?
?拆箱底层实现:
?
? ? ? ?以上就是包装类型的拆箱以及装箱的原理。
?
?
对于Byte、Short、Integer、Long、Character这几种包装类型,当自动装箱的数值在[-128, 127]之间时,不会去创建对象而是从各自对应的缓存区中返回对象,例如:
Long t1 = 128L; Long t2 = 128L; System.out.println(t1 == t2); //false,t1、t2均由new产生新的对象。 Long t3 = 127L; Long t4 = 127L; System.out.println(t3 == t4); //true,从缓存区中取出返回的是同一个对象,==比较的是地址值,所以这里当然返回true了。
?
?实现原理:因为自动装箱会使用valueOf()
public static Long valueOf(long l) { final int offset = 128; if (l >= -128 && l <= 127) { // will cache return LongCache.cache[(int)l + offset]; } return new Long(l); } private static class LongCache { private LongCache(){} static final Long cache[] = new Long[-(-128) + 127 + 1]; static { for(int i = 0; i < cache.length; i++) cache[i] = new Long(i - 128); } }
?
?
?
?
?
?
原文:http://kk-liang.iteye.com/blog/2271534