在Java中,由于基本类型不是继承自Object,为了在泛型代码中可以支持基本类型,Java给每个基本类型都对应了一个包装类型。
比如:
Integer
类概述:
在Java中,可能会使用到int
类型的数据,但可能会有所要求:比如只能使用引用数据类型,但是由于int
类型是基本数据类型,无法直接使用,所以需要进行包装,这就引入了Integer
类,其他基本数据类型的包装类也是这样
Integer
类在对象中包装了一个基本类型 int
的值,该类提供了多个方法,能在 int
类型和 String
类型之间互相转换,还提供了处理 int
类型时非常有用的其他一些常量和方法
使用过程中,装箱和拆箱带来不少的代码量,所以为了减少开发者的负担,java 提供了自动机制。
Integer a = 127;//自动装箱
int b = (int)a;//自动拆箱
【面试题】
public static void main(String[] args) {
Integer a = 127;
Integer b = 127;
Integer c = 128;
Integer d = 128;
System.out.println(a == b);
System.out.println(c == d);
}
运行结果如下:
原因:
打开Interger类中的valueOf方法。
(valueOf() 方法用于返回给定参数的原生 Number 对象值,参数可以是原生数据类型, String等。
该方法是静态方法。)
通过代码看出:i在一定范围内,返回值为固定值 -i+(-IntergerCache.low),我们查看low,hige的值可知low=-128,high=127;
查看IntegerCache源码,IntegerCache是Integer类中的静态内部类,用于缓存数据便于节省内存、提高性能。
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer[] cache;
static Integer[] archivedCache;
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
h = Math.max(parseInt(integerCacheHighPropValue), 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
// Load IntegerCache.archivedCache from archive, if possible
CDS.initializeFromArchive(IntegerCache.class);
int size = (high - low) + 1;
// Use the archived cache if it exists and is large enough
if (archivedCache == null || size > archivedCache.length) {
Integer[] c = new Integer[size];
int j = low;
for(int i = 0; i < c.length; i++) {
c[i] = new Integer(j++);
}
archivedCache = c;
}
cache = archivedCache;
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
- IntegerCache.low = -128
- IntegerCache.high = 127
- 缓冲区cache是一个Integer类型的数组
- IntegerCache缓存区间为[-128,127]。所以,在调用Integer.valueOf(int i)方法进行自动装箱时假若i的值在[-128,127]区间则生成的Integer对象会被存入缓冲区。当再次对该值进行装箱时会先去缓冲区中获取;如果取到则返回,如果没有取到则创建包装类对象存入缓冲区并返回。
题目中,ab值为127,在其范围,127+(-(-128))=255,实现上述过程
cd值为128,则直接返回新创造的包装类,完成自动包装。