java中8种基本类型变量对应的包装类:
byte -- Byte
short -- Short
int -- Integer
long -- Long
float -- Float
Double -- Double
boolean -- Boolean
char -- Character
-
包装类型的自动拆箱与自动装箱实现原理
从JDK1.5之后java引入了自动装箱与自动拆箱技术。
一般我们产生一个对象都是通过new的形式,而包装类型的自动装箱则是这样:
Long t1 = 1000L;
不必感到诧异,其实底层在编译阶段就把上述代码改成:
Long t1 = Long.valueOf(1000L);
---------------------------------------------------------------------------------------------------
拆箱机制:
long t2 = t1;
拆箱底层编译期实现:
long t2 = t1.longValue();
以上就是包装类型的拆箱以及装箱的原理。
-
包装类型缓存区的使用
对于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(),这里只给出Long包装类型底层实现。
- 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);
- }
- }