int和Integer的区别
int和Integer的区别
点击查看示例
public class Test01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a=100;
int b=100;
int c=200;
int d=200;
Integer x=100;
Integer y=100;
Integer o=200;
Integer p=200;
System.out.println(a==b);
System.out.println(c==d);
System.out.println(x==y);
System.out.println(o==p);
System.out.println(a==x);
System.out.println(c==o);
}
}
结果为
true
true
true
false
true
true
原因:
在Integer的底层源码里
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() {}
}
当Integer中定义的值处在-128到127之间时,比较数字的大小
如果不在这个区间内,Integer则会new一个对象
因为Integer o=200
而且200>127
所以会new Integer o;
同理,p也是
而当对象作比较的话比较的是地址,new出来的o,和new出来的p地址不一样
new的Integer对象的地址不一样,所以为false
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义