我创建了一个二维数组,它将存储对父类Student
的子类的对象的引用。
Student[][] a = new Student [5][4];
现在我想用null
初始化这个数组?我该怎么做?一次做的任何伎俩?另外,我想知道是否可以在Java的Base类数组中存储children类的引用?
我想用null
初始化所有值。另外,让我们说一些值被填充,然后我想用null
覆盖这些值。我该怎么做?
答案 0 :(得分:3)
有三种方法,为您选择最优先。
Student[][] a = null; // reference to a equals null
Student[][] a = new Student[5][]; // {null, null, null, null, null}
Student[][] a = new Student[5][5]; // {{null, null, null, null, null}, {...}, ...}
出于您的目的(来自评论),您可以使用Arrays.fill(Object[] a, Object val)
。例如,
for(Student[] array : a) Arrays.fill(array, null);
或
for(int i = 0; i < a.length; ++i)
for(int j = 0; j < a[i].length; ++j)
a[i][j] = null;
另外,我想知道是否可以在Java的Base类数组中存储children类的引用?
是的,这是可能的。名为upcasting的进程(SubStudent
已上传至Student
)。
a[0][0] = new SubStudent();
a[0][1] = new Student();
答案 1 :(得分:2)
默认情况下,JAVA使用null初始化引用对象。