为什么 array[idx++]+="a" 在 Java 8 中增加了一次 idx 而在 Java 9 和 10 中增加了两次?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50683786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 23:45:36  来源:igfitidea点击:

Why does array[idx++]+="a" increase idx once in Java 8 but twice in Java 9 and 10?

javajava-8javacjava-9java-10

提问by Olivier Grégtheitroade

For a challenge, a fellow code golferwrote the following code:

为了挑战,一位代码高尔夫球手编写了以下代码

import java.util.*;
public class Main {
  public static void main(String[] args) {
    int size = 3;
    String[] array = new String[size];
    Arrays.fill(array, "");
    for(int i = 0; i <= 100; ) {
      array[i++%size] += i + " ";
    }
    for(String element: array) {
      System.out.println(element);
    }
  }
}

When running this code in Java 8, we get the following result:

在 Java 8 中运行此代码时,我们得到以下结果:

1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49 52 55 58 61 64 67 70 73 76 79 82 85 88 91 94 97 100 
2 5 8 11 14 17 20 23 26 29 32 35 38 41 44 47 50 53 56 59 62 65 68 71 74 77 80 83 86 89 92 95 98 101 
3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99 

When running this code in Java 10, we get the following result:

在 Java 10 中运行此代码时,我们得到以下结果:

2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100 102 
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100 

The numbering is entirely off using Java 10. So what is happening here? Is it a bug in Java 10?

使用 Java 10 完全不进行编号。那么这里发生了什么?这是 Java 10 中的错误吗?

Follow ups from the comments:

来自评论的跟进:

  • The issue appears when compiled with Java 9 or later (we found it in Java 10). Compiling this code on Java 8, then running in Java 9 or any later version, including Java 11 early access, gives the expected result.
  • This kind of code is non-standard, but is valid according to the spec. It was found by Kevin Cruijssenin a discussion in a golfing challenge, hence the weird use case encountered.
  • Didier Lfound out that the issue can be reproduced with the much smaller and more understandable code:

    class Main {
      public static void main(String[] args) {
        String[] array = { "" };
        array[test()] += "a";
      }
      static int test() {
        System.out.println("evaluated");
        return 0;
      }
    }
    

    Result when compiled in Java 8:

    evaluated
    

    Result when compiled in Java 9 and 10:

    evaluated
    evaluated
    
  • The issue seems to be limited to the string concatenation and assignment operator (+=) with an expression with side effect(s) as the left operand, like in array[test()]+="a", array[ix++]+="a", test()[index]+="a", or test().field+="a". To enable string concatenation, at least one of the sides must have type String. Trying to reproduce this on other types or constructs failed.

  • 使用 Java 9 或更高版本(我们在 Java 10 中发现)编译时会出现此问题。在 Java 8 上编译此代码,然后在 Java 9 或任何更高版本(包括 Java 11 早期访问)中运行,会给出预期的结果。
  • 这种代码是非标准的,但根据规范是有效的。它是由Kevin Cruijssen在一次高尔夫挑战中的讨论中发现的,因此遇到了奇怪的用例。
  • Didier L发现这个问题可以用更小更易理解的代码重现:

    class Main {
      public static void main(String[] args) {
        String[] array = { "" };
        array[test()] += "a";
      }
      static int test() {
        System.out.println("evaluated");
        return 0;
      }
    }
    

    在 Java 8 中编译时的结果:

    evaluated
    

    在 Java 9 和 10 中编译时的结果:

    evaluated
    evaluated
    
  • 这个问题似乎限于字符串连接和赋值运算符(+=)与副作用(一个或多个)的表达式作为左操作数,如在array[test()]+="a"array[ix++]+="a"test()[index]+="a",或test().field+="a"。要启用字符串连接,至少一侧必须具有 type String。尝试在其他类型或构造上重现此失败。

采纳答案by Jorn Vernee

This is a bug in javacstarting from JDK 9 (which made some changes with regard to string concatenation, which I suspect is part of the problem), as confirmed by the javacteam under the bug id JDK-8204322. If you look at the corresponding bytecode for the line:

这是javac从 JDK 9 开始的一个错误(它对字符串连接进行了一些更改,我怀疑这是问题的一部分),正如javac团队在错误 ID JDK-8204322 下确认的那样。如果您查看该行的相应字节码:

array[i++%size] += i + " ";

It is:

这是:

  21: aload_2
  22: iload_3
  23: iinc          3, 1
  26: iload_1
  27: irem
  28: aload_2
  29: iload_3
  30: iinc          3, 1
  33: iload_1
  34: irem
  35: aaload
  36: iload_3
  37: invokedynamic #5,  0 // makeConcatWithConstants:(Ljava/lang/String;I)Ljava/lang/String;
  42: aastore

Where the last aaloadis the actual load from the array. However, the part

最后一个aaload是数组的实际负载。然而,该部分

  21: aload_2             // load the array reference
  22: iload_3             // load 'i'
  23: iinc          3, 1  // increment 'i' (doesn't affect the loaded value)
  26: iload_1             // load 'size'
  27: irem                // compute the remainder

Which roughly corresponds to the expression array[i++%size](minus the actual load and store), is in there twice. This is incorrect, as the spec says in jls-15.26.2:

大致对应于表达式array[i++%size](减去实际加载和存储),在那里两次。这是不正确的,正如jls-15.26.2 中的规范所说:

A compound assignment expression of the form E1 op= E2is equivalent to E1 = (T) ((E1) op (E2)), where Tis the type of E1, except that E1is evaluated only once.

形式的复合赋值表达式E1 op= E2等价于E1 = (T) ((E1) op (E2)),其中T是 的类型E1只是E1只计算一次。

So, for the expression array[i++%size] += i + " ";, the part array[i++%size]should only be evaluated once. But it is evaluated twice (once for the load, and once for the store).

因此,对于表达式array[i++%size] += i + " ";,该部分array[i++%size]应该只计算一次。但它会被评估两次(一次用于负载,一次用于存储)。

So yes, this is a bug.

所以是的,这是一个错误。



Some updates:

一些更新:

The bug is fixed in JDK 11 and there will be a back-port to JDK 10(but not JDK 9, since it no longer receives public updates).

该错误已在 JDK 11 中修复,并且将有一个到 JDK 10后向端口(但不是 JDK 9,因为它不再接收公共更新)。

Aleksey Shipilev mentions on the JBS page(and @DidierL in the comments here):

Aleksey Shipilev 在JBS 页面上提到(和@DidierL 在这里的评论中):

Workaround: compile with -XDstringConcat=inline

解决方法:编译 -XDstringConcat=inline

That will revert to using StringBuilderto do the concatenation, and doesn't have the bug.

这将恢复用于进行StringBuilder连接,并且没有错误。