Java Array of Objects: Creation Guide

In Java, object arrays can be created by following these steps:

  1. First, you need to define a class to represent objects in an array. For example, if we want to create an array to store student objects, we can define a class named Student. An example code for the class is shown below:
public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 省略其他方法和属性的定义
}
  1. Before creating an array of objects, it’s necessary to determine the size of the array. You can use the following syntax to create an object array of a specified size:
Student[] students = new Student[5]; // 创建包含5个元素的对象数组
  1. After creating an array of objects, you can assign values to each array element using the following syntax:
students[0] = new Student("Alice", 18);
students[1] = new Student("Bob", 19);
students[2] = new Student("Charlie", 20);
students[3] = new Student("Dave", 21);
students[4] = new Student("Eve", 22);

This creates an array containing 5 student objects.

The complete sample code is shown below:

public class Main {
    public static void main(String[] args) {
        Student[] students = new Student[5]; // 创建包含5个元素的对象数组

        students[0] = new Student("Alice", 18);
        students[1] = new Student("Bob", 19);
        students[2] = new Student("Charlie", 20);
        students[3] = new Student("Dave", 21);
        students[4] = new Student("Eve", 22);

        // 遍历数组并输出每个学生的信息
        for (Student student : students) {
            System.out.println("Name: " + student.getName() + ", Age: " + student.getAge());
        }
    }
}

The above code will produce the following output:

Name: Alice, Age: 18
Name: Bob, Age: 19
Name: Charlie, Age: 20
Name: Dave, Age: 21
Name: Eve, Age: 22
bannerAds