1. 128陷阱的概念
Java中的“128陷阱”指的是在比较两个Integer对象时,如果它们的值位于-128到127之间(包括-128和127),使用
==
运算符比较可能会返回true
,而超出这个范围的值使用==
比较时几乎总是返回false
。这一现象与Integer类型的自动装箱和缓存机制密切相关。如:
public static void main(String[] args) { int a = 128; int a1 = 128; System.out.println(a==a1); // 输出true int b = 127; int b1 = 127; System.out.println(b==b1);// 输出true Integer c = 127; Integer c1 = 127; System.out.println(c==c1);// 输出true Integer d = 128; Integer d1 = 128; System.out.println(d==d1);// 输出false }
2.产生原因
先来补充一些知识点: 在java的封装类中有两个重要的概念(自动装箱,自动拆箱)
自动装箱与拆箱:
- 自动装箱:Java自动将基本数据类型(如int)转换为对应的包装类类型(如Integer)。例如,
Integer a = 100;
实际上调用了Integer.valueOf(100);
。- 自动拆箱:Java自动将包装类类型转换为基本数据类型。例如,
int b = a;
如果a是Integer类型,则会自动调用a.intValue();
。那么:Java为了提高性能,对Integer类型的值在-128到127之间进行了缓存。当自动装箱时,如果值在这个范围内,Java会直接从缓存中返回对应的Integer对象,而不是创建一个新的对象。当Integer的值超出-128到127的范围时,每次自动装箱都会创建一个新的Integer对象。
3.配合源码更容易理解
Integer.valueOf方法的源码:
low代表的就是-128 high代表的是127 而cache就是在-128~127范围内起到缓存作用的缓存数组
注意:初始化缓存数组(cache)的源码(它负责初始化
Integer
类的缓存机制。这个机制会缓存一定范围内的Integer
对象,以提高性能并减少内存使用。)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; }
java基础--128陷阱
最新推荐文章于 2024-08-04 11:07:52 发布