同String pool 类似的,Java中存在整数(Integer 对象,而非基本类型)pool。在Java中1字节大小以内的Integer(-128到127)都是存在一个常量池中的,(不包含new Integer(xx)初始化),所以他们的引用也是相同的。
例子:
Integer a1 = 127;
Integer b1 = 127;
if(a1==b1){
System.out.println("相等");
}else{
System.out.println("不等");
}
Integer a = 128;
Integer b = 128;
if(a==b){
System.out.println("相等");
}else{
System.out.println("不等");
}
运行结果
相等
不等
因为:a1 b1都是从常亮池中取数据的
源码如下:
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
/**
* The value of the {@code Integer}.
*
* @serial
*/
private final int value; //注意Integer里面的value属性使用final修饰的。
Integer转int会默认调用(注意此处的Integer对象不能为null)
/**
* Returns the value of this {@code Integer} as an
* {@code int}.
*/
public int intValue() {
return value;
}
public static void main(String[] args) {
Integer a=null;
int t=a; //此处会报空指针异常
System.out.println(t);
}