对于挑战,a fellow code golfer wrote 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:
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:
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
使用Java 10完全关闭了编号.那么这里发生了什么?这是Java10中的一个bug吗?
comments 的后续内容:
-
当使用Java 9或更高版本编译时(我们在Java 10中发现了这个问题).在Java 8上编译这段代码,然后在Java 9或任何更高版本(包括Java 11 early access)中运行,可以得到预期的结果.
-
这类代码是非标准的,但根据规范是有效的.它是在discussion in a golfing challenge中被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; } }
Result when compiled in Java 8:
evaluated
Result when compiled in Java 9 and 10:
evaluated evaluated
-
问题似乎仅限于字符串串联和赋值运算符(
+=
),其左操作数为带有副作用的表达式,如array[test()]+="a"
、array[ix++]+="a"
、test()[index]+="a"
或test().field+="a"
.要启用字符串连接,至少有一个边必须具有String
类型.try 在其他类型或构造上复制此操作失败.