后增量后==的令人费解的行为 [英] Puzzling behaviour of == after postincrementation

查看:141
本文介绍了后增量后==的令人费解的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人在一些论坛帖子中假设许多人甚至是经验丰富的Java开发人员都不会理解以下Java代码的和平。

Someone postulated in some forum thread that many people and even experienced Java Developers wouldn't understand the following peace of Java Code.

Integer i1 = 127;
Integer i2 = 127;
System.out.println(i1++ == i2++);
System.out.println(i1 == i2);

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

As a person with some interest in Java I gave it my thoughts and came to the following result.

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否则告诉我。第一行是真的,第二行是假的。

Eclipse tells me otherwise. The first line is true and the second is false.

我真的很感激解释。

第二个问题。这个Java是特定的还是这个例子也适用于基于C的语言?

Second question. Is this Java specific or does this example hold for example for the C based languages, too?

推荐答案

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), 

如果您使用 equals(),则情况2,它将返回true,因为 == 整数运算符仅适用于缓存值。当128超出缓存范围时,128以上的值将不会被缓存,因此您必须使用 equals()方法来检查127以上的两个整数实例是否为 true

In case 2 if you use equals() it'd return true as == operator for integers only works for cached values. as 128 is out of cache range the values above 128 will not be cached, thus youhave to use equals() method to check if two integer instances above 127 are true

TEST:

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

这篇关于后增量后==的令人费解的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆