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

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...