如何在Java中使用null初始化此2D数组?

时间:2016-05-28 13:01:11

标签: java arrays null

我创建了一个二维数组,它将存储对父类Student的子类的对象的引用。

Student[][] a = new Student [5][4]; 

现在我想用null初始化这个数组?我该怎么做?一次做的任何伎俩?另外,我想知道是否可以在Java的Base类数组中存储children类的引用?

我想用null初始化所有值。另外,让我们说一些值被填充,然后我想用null覆盖这些值。我该怎么做?

2 个答案:

答案 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初始化引用对象。