An array of objects is a collection that stores references to instances of a class. This allows you to manage and manipulate multiple objects in a structured manner. Arrays of objects are useful when you need to handle a fixed number of related objects efficiently.
Creating an array of objects involves two main steps:
First, you declare an array that can hold references to objects of a specific class.
ClassName[] arrayName;
Next, you create the array and instantiate its elements.
arrayName = new ClassName[arraySize];
You can combine both steps in a single line:
ClassName[] arrayName = new ClassName[arraySize];
Let’s create an array of Person
objects, where the Person
class has two attributes: name
and age
.
public class Person {
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter for name
public String getName() {
return name;
}
// Getter for age
public int getAge() {
return age;
}
// Overriding toString() method for easy display
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + '}';
}
}
public class Main {
public static void main(String[] args) {
// Declare and instantiate an array of Person objects
Person[] people = new Person[3];
// Initialize the array elements
people[0] = new Person("Alice", 30);
people[1] = new Person("Bob", 25);
people[2] = new Person("Charlie", 35);
// Access and display the array elements
for (Person person : people) {
System.out.println(person);
}
}
}
You can also dynamically initialize the elements of an array of objects, perhaps based on user input or data from a file.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Declare and instantiate an array of Person objects
Person[] people = new Person[2];
// Dynamically initialize the array elements
for (int i = 0; i < people.length; i++) {
System.out.println("Enter name for person " + (i + 1) + ":");
String name = scanner.nextLine();
System.out.println("Enter age for person " + (i + 1) + ":");
int age = scanner.nextInt();
scanner.nextLine(); // Consume newline
people[i] = new Person(name, age);
}
// Access and display the array elements
for (Person person : people) {
System.out.println(person);
}
scanner.close();
}
}
List
.