我创建了一个二维数组,用于存储指向Student
父类的子类对象的引用。
Student[][] a = new Student [5][4];
现在我想用null
初始化这个数组,怎么做?有什么技巧可以一次完成吗?另外,我想知道在Java中是否可能将子类的引用存储在基类的数组中?
我想用null
初始化所有值。此外,假设某些值已经填充,然后我想用null
覆盖这些值。我该怎么做?
有三种方法,请选择最适合您的。
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中是否可以将子类的引用存储在基类的数组中?
是的,这是可能的。这个过程称为向上转型(SubStudent
向上转型为 Student
)。
a[0][0] = new SubStudent();
a[0][1] = new Student();
Arrays.fill
或在for
循环中手动使用a[i][j] = null
。 - Andrew Tobilko
Student[][] a = null;
?你需要更加精确。你可能想要用嵌套的for循环来初始化数组中的所有值为null。 - HopefullyHelpful