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

java – 补充后的==的困惑行为

发布时间:2020-12-14 05:09:30 所属栏目:Java 来源:网络整理
导读:这个问题在这里已经有一个答案: Integer wrapper objects share the same instances only within the value 127? 5个 有人在一些论坛的线索中假设许多人甚至经验丰富的Java开发人员都不了解Java Code的以下和平. Integer i1 = 127;Integer i2 = 127;System.
这个问题在这里已经有一个答案:> Integer wrapper objects share the same instances only within the value 127? 5个
有人在一些论坛的线索中假设许多人甚至经验丰富的Java开发人员都不了解Java Code的以下和平.
Integer i1 = 127;
Integer i2 = 127;
System.out.println(i1++ == i2++);
System.out.println(i1 == i2);

作为对Java有兴趣的人,我给了我想法,并得出以下结果.

System.out.println(i1++ == i2++);
// True,since we first check for equality and increment both variables afterwards.

System.out.println(i1 == i2);
// True again,since both variables are already incremented and have the value 128

Eclipse告诉我.第一行是真实的,第二行是假的.

我真的很感激一个解释.

第二个问题这个Java是否具体,或者这个例子是否适用于C语言?

解决方法

Integer i1 = 127;
Integer i2 = 127;
System.out.println(i1++ == i2++); 
// here i1 and i2 are still 127 as you expected thus true
System.out.println(i1 == i2); 
// here i1 and i2 are 128 which are equal but not cached
    (caching range is -128 to 127),

在情况2中,如果使用equals()它将返回true作为整数的==运算符仅适用于缓存值.由于128超出缓存范围,128以上的值将不会被缓存,因此您需要使用equals()方法来检查127以上的两个整数实例是否为真

测试:

Integer i1 = 126;
    Integer i2 = 126;
    System.out.println(i1++ == i2++);// true
    System.out.println(i1 == i2); //true



 Integer i1 = 126;
        Integer i2 = 126;
        System.out.println(i1++ == i2++);// true
        System.out.println(i1.equals(i2)); //true

  Integer i1 = 128;
        Integer i2 = 128;
        System.out.println(i1++ == i2++);// false
        System.out.println(i1==i2); //false

  Integer i1 = 128;
        Integer i2 = 128;
        System.out.println(i1++.equals(i2++));// true
        System.out.println(i1.equals(i2)); //true

(编辑:李大同)

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

    推荐文章
      热点阅读