最近碰到一个题,如下:
public class Main {
public static void main(String[] args) {
int i1 = 100.0;
int i2 = 100.0;
int i3 = 200.0;
int i4 = 200.0;
System.out.println(i1==i2);
System.out.println(i3==i4);
}
}
最后返回结果是:
true
false
仔细了解了一下,学到了一个新概念,就是java的装箱和拆箱。
1.1什么是拆箱和装箱?
Integer a=5;//装箱
int b=a;//拆箱
简单来说,装箱就是自动将基本数据类型转换为包装器类型;拆箱就是自动将包装器类型转换为基本数据类型。
上图为八种基本数据类型和其对应的包装类。
1.2 装箱和拆箱是如何实现的?
通过代码说明:
首先我们创建一个Main函数,如下:
public class Main {
public static void main(String[] args) {
Integer i = 100;
int j = i;
}
}
编译后打开项目所在路径,找到Main.class文件,用IDEA打开,发现经过编译后的代码如下:
public class Main {
public Main() {
}
public static void main(String[] var0) {
Integer var1 = Integer.valueOf(100);
int var2 = var1.intValue();
} }
可以很清楚的见到程序运行时拆箱和装箱的过程,而且能看到该过程是通过基本数据类型的valueOf()方法去实现的。
1.3分析下源码:
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
//再来看下IntegerCache的源码
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
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) {
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);
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}
通过分析Integer的源码我们既可以明白最上边的那个问题为啥是true和false了。
源码给定的范围是-128~127,也就是说在这个范围内的话,直接取,不必再创建对象了,所以上面的两个变量自然指向同一地址,最后结果返回true,而若是超过范围,则需要装箱,也就是创建一个新的对象,那么两个变量就各自分配到了一个新的地址,结果自然为true。
其中应该还涉及到一部分常量池的内容,等抽空儿再详细的写一下。