包装类
提到128陷阱就不得先说一下包装类
1.为什么有包装类
- 在面向对象中,“一切皆对象”,但基本数据类型的数据不太符合这一理念,基本数据类型不是对象
- .涉及到类型之间的转化,数据类型之间的基本操作;如果都有我们自己去实现,那么工作量过大。
所以java针对每一个基本数据类型都设计了一个包装类
包装类的基本操作
2自动拆装箱
1.装箱:把基本类型数据转成对应的包装类对象。
方式一:Integer i = Integer.valueOf(13);
方式二:Integer i = new Integer(13);
2.拆箱:把包装类对象转成对应的基本数据类型数据。
int value = i.intValue();
自动装箱(Autoboxing)和自动拆箱(AutoUnboxing)
在Java 5之前的版本中,基本数据类型和包装类之间的转换是需要手动进行的,但Sun公司从Java5开始提供了的自动装箱(Autoboxing)和自动拆箱(AutoUnboxing)操作 ;
自动装箱:可以把一个基本类型变量直接赋给对应的包装类型变量。
比如:Integer i = 13;
自动拆箱:允许把包装类对象直接赋给对应的基本数据类型变量。
比如:Integer i = new Integer(13); Int j = i;
128陷阱
首先看一道面试题
public static void main(String[] args) {Integer num1 = 100;Integer num2 = 100;System.out.println(num1 == num2);Integer num3 = 128;Integer num4 = 128;System.out.println(num3 == num4);
}
answer: true false
接下来从源码解析为何会有128陷阱:
首先来看valueOf()函数源码:
public static Integer valueOf(int i) {if (i >= IntegerCache.low && i <= IntegerCache.high)return IntegerCache.cache[i + (-IntegerCache.low)];return new Integer(i);}
可以看出i和一个IntegerCache的长度进行比较,如果在这个Cache里面,返回cache里的东西,在cache外面就new出一个新的Integer对象。
接下来我们看这个Cache
private static class IntegerCache {static final int low = -128;static final int high;static final Integer cache[];static {// high value may be configured by propertyint 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_VALUEh = 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() {}}
可以看出这个cache的范围是【-128,127】,在这个范围内的数都被存储到一个数组里,不在这个范围内的则另外开辟一块内存空间。
按照我的理解,cache相当于Integer的一个缓存数组,当我们在-128-127之间进行自动装箱的时候,我们就直接返回该值在内存当中的地址。
回到刚刚的面试题128不在这个范围内,自然地址位置不相同。
这就是所谓的128陷阱。