欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

项目中遇到的Integer问题--转

发布时间:2025/4/5 编程问答 25 豆豆
生活随笔 收集整理的这篇文章主要介绍了 项目中遇到的Integer问题--转 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

Integer类型值相等或不等分析

http://www.cnblogs.com/zzllx/p/5778470.html

看到博客园一位博友写的面试问题,其中一题是 Integer a = 1; Integer b = 1 ; (a == b)?true :false; 当时我一看,这不是明显的true 嘛,  看到评论讨论才知道,对于Integer值比较 有范围规定   。平时都是用equals做比较判断,简单省事。没注意到这些细节。正好趁此机会好好谷歌了一下,以此做个备份。

     用以下代码做测试

 

1 @Test2 public void testInteger() {3 Integer a = -129;4 Integer a1 = -129;5 Integer aaa = new Integer(-129);6 7 Integer aa = -128;8 Integer aa1 = -128;9 10 System.out.println("a==a1:" + (a == a1) + "--aa==aa1:" + (aa == aa1)); // a==a1:false--aa==aa1:true 11 System.out.println("aaa==a1:" + (aaa == a1)); // aaa==a1:false 12 System.out.println("a.equals(a1):" + a.equals(a1)); // a.equals(a1):true 13 14 Integer b = 128; 15 Integer b1 = 128; 16 System.out.println("b==b1:" + (b == b1)); // b==b1:false 17 System.out.println("b.equals(b1):" + b.equals(b1)); // b.equals(b1):true 18 19 Integer c = 127; 20 Integer cc = 127; 21 Integer d = 1; 22 Integer dd = 1; 23 24 System.out.println("c==cc:" + (c == cc) + "----d==dd:" + (d == dd)); // c==cc:true----d==dd:true 25 System.out.println("------------"); 26 27 Integer e = 128; 28 int e1 = 128; 29 System.out.println("e == e1:" + (e == e1)); // e == e1:true 30 }

      得出的结论是  Integer 类型的值在[-128,127] 期间,Integer 用 “==”是可以的。  为什么会出现这个情况呢,实际上在我们用Integer a = 数字;来赋值的时候Integer这个类是调用的public static Integer valueOf(int i)这个方法。

     

     

     

 

 

        我们来看看ValueOf(int i)的代码,可以发现他对传入参数i做了一个if判断。在-128<=i<=127的时候是直接用的int原始数据类型,而超出了这个范围则是new了一个对象。我们知道"=="符号在比较对象的时候是比较的内存地址,而对于原始数据类型是直接比对的数据值。那么这个问题就解决了。

       还有一点需要注意到 是   Integer e = 128; int e1 = 128;  e == e1:true  而  Integer b = 128; Integer b1 = 128;   b==b1:false   ,e=128 已经大于127了,所以e 是一个对象(new 出来的) 为什么e = e1 是ture , 因为  int为值类型,引用类型Integer与值类型int比较显然比较的是值因为int在堆中是不开辟内存的,他在栈中的值则为他本身的值所以e==e1比较的是他们各自的value, e==e1为true

     总结:Integer 类型的值在[-128,127] 期间,Integer 用 “==”是可以的   , Integer  与 int 类型比较(==)比较的是值。

转载于:https://www.cnblogs.com/davidwang456/p/5784949.html

总结

以上是生活随笔为你收集整理的项目中遇到的Integer问题--转的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。