当两个对象进行比较的时候,我们应该使用equals方法,但是由于基础类型在1.5以前的jdk,大家已经习惯了 == 的方式,所以有时候,会马虎大意依然使用 == ?进行比较,那么这样会有什么问题吗?结果是什么?
? 1 2 3 4 5 6 7 8 9 10 11monospace !important; border: 0px !important; border-radius: 0px !important; float: none !important; height: auto !important; line-height: 1.1em !important; overflow: visible !important; vertical-align: baseline !important; width: auto !important; background: none !important;" class="java plain">Long a2 = 127L;
Long b2 = 127L;
System.out.println(a2 == b2);
?
结果是true,竟然是true???
?
Long a3 = 128L;
Long b3 = 128L;
System.out.println(a3==b3);
?
结果是false
这样结果的原因是Long类型内部有一个内部类,维护了一个cache,
见Long源码 552行
? 1 2 3 4 5 6 7public static Long valueOf(long l) {
????final int offset = 128;
????if (l >= -128 && l <= 127) { // will cache
????????return LongCache.cache[(int)l + offset];
????}
????????return new Long(l);
}
见Long源码 528行
? 1 2 3 4 5 6 7 8 9 10private static class LongCache {
????private LongCache(){}
?
????static final Long cache[] = new Long[-(-128) + 127 + 1];
?
????static {
????????for(int i = 0; i < cache.length; i++)
????????cache[i] = new Long(i - 128);
????}
????}
-128到127直接的值都放在cache里,不会创建新的对象,所以==比较的时候,结果是正确的,
当超过这个范围,因为是创建的新对象,所以自然不会相等