加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 06:21:48 所属栏目:Java 来源:网络整理
导读:Integer类型值相等或不等分析 http://www.cnblogs.com/zzllx/p/5778470.html 看到博客园一位博友写的面试问题,其中一题是 Integer a = 1; Integer b = 1 ; (a == b)?true :false; 当时我一看,这不是明显的true 嘛, ?看到评论讨论才知道,对于Integer值

Integer类型值相等或不等分析

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

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

? ? ?用以下代码做测试

<div class="cnblogs_code">
<div class="cnblogs_code_toolbar"><span class="cnblogs_code_copy"><a title="复制代码">

<img src="https://www.52php.cn/res/2019/02-12/10/51e409b11aa51c150090697429a953ed.gif" alt="复制代码">

 1      @Test
 2     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,Integer 用 “==”是可以的 ? , Integer ?与 int 类型比较(==)比较的是值。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读