public static void main(String[] args) {
Double i1 = 100.0;
Double i2 = 100.0;
Double i3 = 200.0;
Double i4 = 200.0;
System.out.println(i1==i2);//false
System.out.println(i3==i4);//false
}
图1 Double比较
public static void main(String[] args) {
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 200;
Integer i4 = 200;
System.out.println(i1==i2);//true
System.out.println(i3==i4);//false
}
图2 Integer比较
图一八股文通常介绍:原因: 在某个范围内的整型数值的个数是有限的,而浮点数却不是。
你这里是不是好奇,为什么浮点数不是?
先跟图2的八股文介绍一样贴出代码:
public static Double valueOf(double d) {
return new Double(d);
}
图2八股文通常介绍:
输出结果表明i1和i2指向的是同一个对象,而i3和i4指向的是不同的对 象。此时只需一看源码便知究竟,下面这段代码是Integer的valueOf方法的具体实现:
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
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) {
try {
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);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
从这2段代码可以看出,在通过valueOf方法创建Integer对象的时候,如果数值在[-128,127]之间, 便返回指向IntegerCache.cache中已经存在的对象的引用;否则创建一个新的Integer对象。
上面的代码中i1和i2的数值为100 ,因此会直接从cache中取已经存在的对象,所以i1和i2指向的是 同一个对象,而i3和i4则是分别指向不同的对象。
疑问点:上面都告诉了你,它们都是采用的相应的valueOf(...);但是你好奇真的是这样吗?为什么是这样的?
调试方法:将你的编译后文件进行反编译,这样你就可以看出你的代码是怎么执行的了
idea进入你需要调试的方法所在位置,找到编译后相应所在位置的文件夹,右击-openIn->terminal;xxxx需要替换为你编译后的文件名
javap -verbose -c xxxx.class
你就会看见:
- Constant Pool: 常量池中的条目列表,包括类名、字段、方法和接口的符号引用。
回过头你就能清楚了,你也可以告诉面试官如何得知的那部分代码编译的时候是使用了相应的valueOf(...)等等。