How to initialize an array of objects in Java
Here is an example of how you can initialize an array of objects in Java:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// getters and setters
}
Person[] people = new Person[] {
new Person("Alice", 30),
new Person("Bob", 35),
new Person("Charlie", 40)
};
This creates an array of Person
objects with three elements, each initialized with a different name and age.
Alternatively, you can use an array initializer to create an array and initialize its elements in a single step:
Person[] people = {
new Person("Alice", 30),
new Person("Bob", 35),
new Person("Charlie", 40)
};
This is equivalent to the first example.
You can also use a loop to initialize an array of objects:
Person[] people = new Person[3];
for (int i = 0; i < people.length; i++) {
people[i] = new Person("Person " + i, i * 10);
}
This creates an array of Person
objects with three elements, each initialized with a different name and age.