要定义和初始化 Java 类的数组,可以使用以下步骤:定义数组:ClassName[] arrayName = new ClassName[size];初始化数组:ClassName[] arrayName = new ClassName[]{element1, element2, ..., elementN};

如何定义和初始化 Java 类的数组
定义
要定义一个类的数组,语法如下:
ClassName[] arrayName = new ClassName[size];
其中:
立即学习“Java免费学习笔记(深入)”;
-
ClassName是要创建的类的名称。 -
arrayName是数组的名称。 -
size是数组的长度,它指定了数组中元素的数量。
初始化
要初始化数组,可以在创建数组时提供元素值,如下所示:
ClassName[] arrayName = new ClassName[]{element1, element2, ..., elementN};其中:
立即学习“Java免费学习笔记(深入)”;
-
element1,element2, ...,elementN是要初始化数组的元素值。
示例
以下示例演示了如何定义和初始化一个 Student 类的数组:
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
Student[] students = new Student[]{
new Student("Alice", 20),
new Student("Bob", 21),
new Student("Carol", 22)
};
}
}在本示例中:
-
students是一个Student类的数组。 - 数组
students已通过三种不同的Student对象进行初始化。











