您的位置:首页 > 编程语言 > Java开发

Java Integer之间==问题

2016-03-21 15:56 489 查看
public class Main {

public static void main(String[] args) {
Integer i = 1000 ;
Integer j = 1000 ;
Integer x = 100 ;
Integer y = 100 ;
Integer m = new Integer(100) ;
Integer n = i ;
System.out.println(i==j);
System.out.println(x==y);
System.out.println(x==m);
System.out.println(i==n);
}

}


输出:
false
true
false
true


源码

//如果是在-128到正的127之间就返回缓存里面的值。

public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}

//缓存的代码

private static class IntegerCache {
private IntegerCache(){}

static final Integer cache[] = new Integer[-(-128) + 127 + 1];

static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Integer(i - 128);
}
}


在-128<=i<=127的时候是直接用的int原始数据类型,而超出了这个范围则是new了一个对象。
java对小整形对象的优化, [-128,127]这个范围的整数值在程序中出现次数多,这样处理可以减少内存中对象的数量。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: