解析源码
在Java中基础类型包装类中的Integer和 Long有一个特殊的地方需要注意
在比较值的时候不要用 == 进行比较。
在这里以 Long 类型为例
查看源码: Long.java
public static Long valueOf(long l) {
final int offset = 128;
// -128 到 127 之间的数值会被缓存起来
if (l >= -128 && l <= 127) { // will cache
return LongCache.cache[(int)l + offset];
}
return new Long(l);
}
private 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);
}
}
再查看Integer.java,发现也有类似的缓存
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
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() {}
}
测试案例
测试案例:
Long num1 = -129L;
Long num2 =-129L;
Long num3 =-128L;
Long num4 =-128L;
Long num5 = 127L;
Long num6 = 127L;
Long num7 = 128L;
Long num8 = 128L;
System.out.println("-129L == -129L " +(num1 == num2));
System.out.println("-128L == -128L " +(num3 == num4));
System.out.println("127L == 127L " +(num5 == num6));
System.out.println("128L == 128L " +(num7 == num8));
结果如下:
如何比较
那么我们改如何比较呢,方法有如下几种
第一种: longValue 或 intValue
第二种: compareTo 或者 compare
第三种: 使用equals
第三种方法也是使用的第一种,Long重写了equals方法
案例:
Long num1 = -129L;
Long num2 =-129L;
System.out.println(num1.longValue() == num2.longValue());
System.out.println(num1.equals(num2));
//System.out.println(num1.doubleValue() == num2.doubleValue());
System.out.println(num1.intValue() == num2.intValue());
System.out.println(num1.compareTo(num2));// num1 < num2 返回 -1 num1 == num2 返回0 num1 > num2 返回1
System.out.println(Long.compare(num1, num2));// num1 < num2 返回 -1 num1 == num2 返回0 num1 > num2 返回1
结果如下:
版权声明:本文为weixin_43863895原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。