回答您的问题:是的,有区别(请参阅JavaDoc)。
您的第一个版本将一个对象实例放入一行的每个数组元素中。因此,对该实例的更改在数组同一行中的每个元素中都是可见的。您i
ClassB
总共将拥有实例。
第二个版本将它自己的实例放入每个数组元素中。您i*j
ClassB
总共将拥有实例。
您的代码的第一个版本相当于
for (ClassB[] classB_1Array : classB_2Array) {
ClassB instance = new ClassB();
Arrays.fill(classB_1Array, instance);
}
希望这些信息对您有所帮助,我没有查看您的 pastebin 代码。
编辑:
为了澄清您的误解,请仔细查看该程序的输出:
import java.util.Arrays;
public class ArrayFiller {
public static void main(String[] args) {
// your first version:
Person[][] yourFirstVersion = new Person[2][2];
for (Person[] array : yourFirstVersion) {
Arrays.fill(array, new Person("Mike"));
}
System.out.println(Arrays.deepToString(yourFirstVersion));
yourFirstVersion[0][1].setName("Paul");
System.out.println(Arrays.deepToString(yourFirstVersion));
System.out.println("-----");
// equivalent: my version:
Person[][] myVersion = new Person[2][2];
for (Person[] array : myVersion) {
Person person = new Person("John");
Arrays.fill(array, person);
}
System.out.println(Arrays.deepToString(myVersion));
myVersion[0][1].setName("Thomas");
System.out.println(Arrays.deepToString(myVersion));
System.out.println("-----");
// your second version
Person[][] yourSecondVersion = new Person[2][2];
for (int i = 0; i < yourSecondVersion.length; i++) {
for (int j = 0; j < yourSecondVersion[i].length; j++) {
yourSecondVersion[i][j] = new Person("Max");
}
}
System.out.println(Arrays.deepToString(yourSecondVersion));
yourSecondVersion[0][1].setName("Chris");
System.out.println(Arrays.deepToString(yourSecondVersion));
}
private static class Person {
private String name;
public Person(String name) {
System.out.println("Constructor called for " + name);
this.name = name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
}
这是输出:
Constructor called for Mike
Constructor called for Mike
[[Mike, Mike], [Mike, Mike]]
[[Paul, Paul], [Mike, Mike]]
-----
Constructor called for John
Constructor called for John
[[John, John], [John, John]]
[[Thomas, Thomas], [John, John]]
-----
Constructor called for Max
Constructor called for Max
Constructor called for Max
Constructor called for Max
[[Max, Max], [Max, Max]]
[[Max, Chris], [Max, Max]]