Java中2个Integer比较相同的四种方式举例
Java中2个Integer比较相同的4种方式
概要
使用前切记Integer的范围是 【 -128 ~ 127】例如:Integer a = 128; Integer b = 128;
1,使用== 比较
【-128 ~ 127】区间内返回true,否则返回false
// == 比较
if (a == b){
System.out.println("a,b使用==比较 返回结果:true");
}else {
System.out.println("a,b使用==比较 返回结果:false");
}
返回false
2,使用equals比较
// equals比较
if (a.equals(b)){
System.out.println("a,b使用equals比较 返回结果:true");
}else {
System.out.println("a,b使用equals比较 返回结果:false");
}
返回true,因为点击内部equals方法发现,核心比较的Integer的intValue()值
// 点击equals时进入该方法
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
3,使用intValue比较
if (a.intValue() == b.intValue()){
System.out.println("a,b使用intValue比较 返回结果:true");
}else {
System.out.println("a,b使用intValue比较 返回结果:false");
}
返回true,核心比较的也是Integer的intValue()值
4,使用 compareTo比较
// compareTo比较
if (a.compareTo(b) == 0){
System.out.println("a,b使用compareTo比较 返回结果:true");
}else {
System.out.println("a,b使用compareTo比较 返回结果:false");
}
返回true,核心比较的是int值
// 点击compareTo时进入该方法
// 第一级
public int compareTo(Integer anotherInteger) {
return compare(this.value, anotherInteger.value);
}
// 第二级
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
总结
Integer大于127后不能用==比较的原因是因为Java的自动装箱机制和Integer对象的缓存机制,如果是在区间内则从缓存中获取返回,否则创建一个新的Integer对象,源码如下:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}

如果你要赋的值在这【-128 ~ 127】区间内,他就会把变量a,b当做一个个变量,放到内存中;但如果不在这个范围内,就会去new一个Integer对象
经过测试,
1》 Integer在【-128 ~ 127】范围内时,4个方法返回都是true,
2》 小于-128或者大于127时,==返回是false,其余3种方法返回的都是true。
到此这篇关于Java中2个Integer比较相同的四种方式的文章就介绍到这了,更多相关Java中Integer比较相同内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
在SpringBoot3中spring.factories配置不起作用的原因和解决方法
本文给大家介绍了在SpringBoot3中spring.factories配置的自动装配不生效的原因和解决方法,文中通过代码和图文给出了详细的解决方法,具有一定的参考价值,需要的朋友可以参考下2024-02-02
SpringCache缓存抽象之CacheManager与自定义键生成方式
本文将深入探讨Spring Cache的核心组件CacheManager及自定义键生成策略,帮助开发者掌握缓存配置与优化技巧,从而构建高效可靠的缓存系统,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2025-04-04


最新评论