Integer 是最常用的包装类之一,面试官特别喜欢结合 equals() 和 == 来问问题。
那么 Integer 究竟应该怎么学才算是掌握呢?应该掌握哪些知识点呢?
简单介绍
首先先聊一下什么是包装类。在Java中有 8 大基本数据类型,每个数据类型都有对应的包装类,包装类的作用就是将数据封装成类和对象,同时赋予了包装类很多实用的方法来操作这些数据,一句话总结就是,包装类提供了处理基本数据类型的很多方法,让它们成为一个对象。
接下来讲解 Integer 的底层原理:
Integer 的成员变量
对于 Integer 来说,真正核心的变量只有一个,它被用来存放 Integer 的值:
private final int value;
Integer 还有一个很重要的缓冲池,里面存放了已经初始化好的 -128~127 对象:
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[]; // 缓存数组, 存放 -128~127 缓存对象
static {
// 省略对cache进行初始化的代码
// 在加载 Integer 时, 会自动装载 cache 缓存, 将 -128~127 添加到缓存池
}
private IntegerCache() {}
}
Integer 的重要方法
intValue() 和 valueOf() 方法是 int 和 Integer 进行相互转化的关键。
// 返回 Integer 的 int 值
public int intValue() {
return value;
}
// 将 int 转化为 Integer 对象
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
面试官怎么问?
1.两个 Integer 类型变量用 == 比较
// 1.使用 new 创建不同对象
Integer a0 = new Integer(1);
Integer b0 = new Integer(1);
// a0 == b0 结果:false, 比较的是不同对象的地址
// 2.调用intValue方法得到其int值
Integer a0 = new Integer(1);
Integer b0 = new Integer(1);
//a0.intValue() == b0.intValue(), 结果为 true, 比较的是 int 值
// 3.把Integer类型的变量拆箱成int类型
int c = 1;
Integer a0 = new Integer(1);
// a0 == c, 结果为true, a0先拆箱,变成 int 类型再和 c 比较
// 4.在 -128~127 值之间的比较
Integer a1 = 30;
Integer b1 = 30;
// a1 == b1, 结果为 true, 因为比较的是缓冲池中的同个对象
// 5.在 -128~127 之外的比较
Integer a3 = 128;
Integer b3 = 128;
// a3 == b3, 结果为 false, 因为128 超出缓冲池最大范围, a3 和 b3 都是新 new 出来的
2.Integer 的 equals() 怎么实现?
先判断比较对象是不是 Integer 类型,如果是则调用 intValue() 方法判断 两个对象的 int 值是否相等。
源码:
public boolean equals(Object obj) {
if (obj instanceof Integer) { // obj 是否 Integer类型
return value == ((Integer)obj).intValue(); // 调用intValue()方法, 比较int值
}
return false;
}
脚踏实地,仰望星空。