Foreach和制作新对象会产生空值

Mat*_*ski 0 java

我有一段代码:

public class Main {
    static String strings[];

    public static void main(String[] args) {
        strings = new String[10];
        for (String s : strings) {
            s= new String("test");
        }

        for (String s : strings) {
            System.out.println(s);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

为什么所有字符串仍然包含null而不是"test"?

joh*_*902 6

增强的for语句(for-each循环)相当于:

T[] a = strings;
for (int i = 0; i < a.length; i++) {
    String s = a[i];
    s = new String("test");
}
Run Code Online (Sandbox Code Playgroud)

所以你的问题与这种情况类似:

String a = null;
String b = a;
b = new String("test");
System.out.println(a); // null
Run Code Online (Sandbox Code Playgroud)