回顾了一下java基础,在包装类与基本数据类型的时候卡壳了;
看一下代码:
package com.liuzm.test;
import org.junit.Test;
public class NumberTest {
@Test
public void testNum() {
Integer a = 100;
Integer b = 100;
System.out.println(a == b);//true
}
}
和以前记得一样,-128-127是true,以前也没有深入了解过,也没有这么写过代码;现在有时间就认真看看,JDK自带的反编译工具javap反编译一下NumberTest.class文件,结果如下图:
其中Integer a = 100,编译后Integer a = Integer.valueOf(100);
Integer b = 100,编译后Integer b = Integer.valueOf(100);
idea ctrl+N输入Integer,按下alt+7,找到valueOf方法;
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
到这里大家可能会怀疑与IntegerCache有关,没错,真相只有一个;接着看IntegerCache,它是一个静态内部类,重要属性cache,被static final修饰;
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;
//测试integerCacheHighPropValue = null;
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;
//初始化数组长度为256
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() {}
}
从这里就可以看出为什么比较时-128~127是true;超出这个范围就是false(return new Integer(i));
Integer这可以搞一段落;来看看其他包装类(整形),我猜想也都差不多,果然不出所料:
public 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);
}
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);
}
}
自己也可以看一下,Byte,Short包装类是不是一样,相对于Integer,其它三个感觉上代码更简洁,更容易理解;