后增量后==的令人费解的行为

Auf*_*ind 9 java post-increment

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

Integer i1 = 127;
Integer i2 = 127;
System.out.println(i1++ == i2++);
System.out.println(i1 == i2);
Run Code Online (Sandbox Code Playgroud)

作为一个对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
Run Code Online (Sandbox Code Playgroud)

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

我真的很感激解释.

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

Per*_*ror 14

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), 
Run Code Online (Sandbox Code Playgroud)

在情况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
Run Code Online (Sandbox Code Playgroud)

  • 需要注意的是,我认为缓存范围是特定于JVM的实现,而不是JLS的一部分.因此,不保证此行为在JVM之间保持一致. (4认同)