java类类型数组怎么赋值

Java 中为类类型数组赋值的方法有:使用数组初始化器:ClassType[] array = { new ClassType1(), new ClassType2(), ... }使用循环赋值:ClassType[] array = new ClassType[size]; for (int i = 0; i

如何在 Java 中为类类型数组赋值?

方法:

在 Java 中,可以通过以下方法为类类型数组赋值:

1. 使用数组初始化器:

ClassType[] array = { new ClassType1(), new ClassType2(), ... };

2. 使用循环赋值:

ClassType[] array = new ClassType[size];
for (int i = 0; i < size; i++) {
  array[i] = new ClassType();
  // 或 array[i] = (ClassType) new Object();
}

3. 使用 Arrays.fill() 方法:

ClassType[] array = new ClassType[size];
Arrays.fill(array, new ClassType());

示例:

// 创建一个包含三个 Student 类型的数组
Student[] students = new Student[3];

// 使用数组初始化器赋值
students[0] = new Student("John", 21);
students[1] = new Student("Alice", 20);
students[2] = new Student("Bob", 22);

// 使用循环

赋值 students = new Student[5]; for (int i = 0; i < students.length; i++) { students[i] = new Student("Student" + (i + 1), i + 10); } // 使用 Arrays.fill() 方法赋值 students = new Student[10]; Arrays.fill(students, new Student("Default Student", 0));