Integer的自动装箱和自动拆箱、与int的区别
第一次写博客,因为偶尔看到一道题,自己做错了,所以花了些时间研究了一下,或许存在错误,希望大家指出,相互学习。
一、Integer的自动装箱和自动拆箱
Integer类包装一个对象中的原始类型int的值。 类型为Integer的对象包含一个单一字段,其类型为int 。
此外,该类还提供了一些将int转换为String和String转换为int ,以及在处理int时有用的其他常量和方法。
首先来了解一下Java的自动装、拆箱原理:
1.自动装箱:自动将基本数据类型(int)转换为其对应的包装器类型(Integer)
Integer a = 100;
// 此时会进行装箱,调用Integer.valueOf(int i)方法,如果范围在[-128,127]直接返回当前的缓存值,
// 否则重新new一个新的Integer
执行代码会进入到以下Integer的这段源码:
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
//这个源码断点进来了,只要i的值再[-128,127]区间,都是返回cache数组的对应i的对象地址值,否者重新new Integer
2.自动拆箱:拆箱就是自动将包装器类型转换为基本数据类型
Integer a = 100;
int i = a;
// 此时会进行自动拆箱,调用intValue()方法,返回一个int类型值a
会进入Integer的这段源码:
/**
* Returns the value of this {@code Integer} as an
* {@code int}.
*/
public int intValue() {
return value;
}
二、Integer和int的比较(面试题)
Integer a = new Integer(127);
Integer b = new Integer(127);
int c = 500;
int d = 500;
Integer e = 127;
Integer f = 127;
System.out.println(a == b);
System.out.println(c == d);
System.out.println(a == c);
System.out.println(a.equals(b));
System.out.println(e == f);
System.out.println(a == e);
结果为:
false
true
true
true
true
false
再看这道题的答案时,先了解一下==运算符和equals()方法
- ==运算符
如果是基本数据类型,比较的是值大小;如果是引用类型,比较的是引用地址值 - equals()方法
如果引用类型重写了equals()方法,按重写规则比较,比如String、Integer重写的equals()方法按照值比较,否则按照引用地址值比较
(1) a == b,自然比较的是Integer对象的地址值
(2) c == d,都是基本数据类型,比较值
(3) a == c,a为Integer,c为int,如果进行比较会拆箱把Integer变为int然后再进行a==c比较
(4) a.equals(b),比较值
(5) e == f,e和f左边都是Integer,右边为int值,所以会装箱,把int类型的127通过valueOf()方法装箱为Integer,所以,需要考虑是否在[-128,127]区间,如果在区间地址值相同,不在地址值不同
(6) a == e,a因为是直接通过new关键字,而e是装箱,地址值不一致的。
总结:
- 牢记Integer的范围[-128,127],在范围返回,不在范围new
- “==”符号,如果为基本数据类型比较,比较的是值;如果为对象类型比较,则比较的是地址值