微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

这个问题在这里已经有一个答案:> 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

原文地址:https://www.jb51.cc/java/123356.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐