Java是一个纯面向对象的语言,但是为了编程的方便还是引入了基本数据类型。在Java中共有8种基本数据类型。但为了能够将这些基本数据类型当成对象操作,Java就引入了包装类型(Wrapper Class), int的包装类型就是Integer
8种基本数据类型:byte short int long float double char boolean
对应的包装类型 Byte Short Integer Long,Float Double Character Boolean
class AutoUnboxingTest {
public static void main(String[] args) {
Integer a = new Integer(3);
Integer b = 3; // 将3自动装箱成Integer类型
int c = 3;
System.out.println(a == b); // false 两个引用没有引用同一对象
System.out.println(a == c); // true a自动拆箱成int类型再和c比较
}
}
还有一个自动装箱和猜想的面试题:
public class Test03 {
public static void main(String[] args) {
Integer f1 = 100, f2 = 100, f3 = 150, f4 = 150;
System.out.println(f1 == f2);
System.out.println(f3 == f4);
}
}
这里如果不明白,就会很容易出错。首先要知道f1, f2, f3, f4都是对象的引用,并且给他们了一个基本数据类型的值。如果这些值都是在常量池中获取的,那么他们的结果都应该是true。但是如果都是重新创建了一个对象那么结果就应该为false。
实际上,在给对象赋值时,调用了integer的静态方法valueOf,如果你看到了valueOf的源代码就知道发生了什么。
/**
* 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);
}
意思就是说 在调用自动装箱和拆箱的的时候默认是在-128到127之间。那就是说 如果基本数据是-128到127之间就会在cache中取值,也就是常量池。不在该范围会重新创建对象。所以上面面试的结果为
f1 == f2 是true f3==f4是 false