我有一段代码:
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);
}
}
}
为什么所有字符串仍然包含null而不是“test”?
答案 0 :(得分:6)
增强的for语句(for-each循环)等同于:
T[] a = strings;
for (int i = 0; i < a.length; i++) {
String s = a[i];
s = new String("test");
}
所以你的问题与这种情况类似:
String a = null;
String b = a;
b = new String("test");
System.out.println(a); // null
答案 1 :(得分:1)
public class Main {
static String strings[];
public static void main(String[] args) {
strings = new String[10];
for (int i = 0; i < strings.length; ++i) {
strings[i] = new String("test");
}
for (String s : strings) {
System.out.println(s);
}
}
}
答案 2 :(得分:1)
要打印“测试”,请尝试以下操作:
public class Main { static String strings [];
public static void main(String[] args) {
strings = new String[10];
for (int i=0; i<strings.length(); i++) {
strings[i]= new String("test");
}
for (String s : strings) {
System.out.println(s);
}
}
}
答案 3 :(得分:-1)
禁止在For-each循环中为迭代数组进行赋值。