简体   繁体   English

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

[英]How do I initialize this 2D array with null in Java?

I have made a 2-d array which will store references to objects of the children classes of parent class Student . 我制作了一个二维数组,该数组将存储对父类Student的子类对象的引用。

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

Now I want to initialize this array with null ? 现在我想用null初始化此数组? How do I do it? 我该怎么做? Any trick to doing it at once? 一次完成任何技巧? Also, I Wanted to know if it is possible to store references of children class in an array of Base class in Java? 另外,我想知道是否可以将子类的引用存储在Java基类的数组中?

I want to initialize all the values with null . 我想用null初始化所有值。 Also, let's say some values are filled and then I want to overwrite the values with null . 另外,假设填充了一些值,然后我想用null覆盖这些值。 How do I do that? 我怎么做?

There are three ways, choose the most priority for you. 您可以通过三种方式为您选择最优先的选项。

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}, {...}, ...}

For your purpose (from the comment), you could use Arrays.fill(Object[] a, Object val) . 为了您的目的(从注释中),您可以使用Arrays.fill(Object[] a, Object val) For example, 例如,

for(Student[] array : a) Arrays.fill(array, null);

or 要么

for(int i = 0; i < a.length; ++i)
    for(int j = 0; j < a[i].length; ++j)
        a[i][j] = null;

Also, I Wanted to know if it is possible to store references of children class in an array of Base class in Java? 另外,我想知道是否可以将子类的引用存储在Java基类的数组中?

Yes, that's possible. 是的,那是可能的。 The process named upcasting ( SubStudent is upcasted to Student ). 名为upcasting的过程( SubStudentSubStudentStudent )。

a[0][0] = new SubStudent();
a[0][1] = new Student();

默认情况下,JAVA使用空值初始化参考对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM