An array of objects is a way to store multiple instances of a class in a single data structure, making it useful for managing collections of complex data.
To create an array of objects, you define the array with the class name as the data type. Here’s an example where we create an array to hold instances of a Student
class:
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
With this class defined, we can now create an array of Student
objects:
Student[] students = new Student[3]; // Creates an array of 3 Student objects
At this point, the students
array holds null
values because the Student
objects haven’t been instantiated yet. We can initialize each element in the array with new instances:
students[0] = new Student("Alice", 20);
students[1] = new Student("Bob", 22);
students[2] = new Student("Charlie", 19);
You can access and work with each object in the array using indexing:
students[0].displayInfo(); // Outputs: Name: Alice, Age: 20
Looping through the array allows you to perform actions on each object, such as displaying information or updating data:
for (Student student : students) {
student.displayInfo();
}
null
.ArrayList
instead of arrays, especially when handling a variable number of objects.Consider a scenario where you want to store and manage data on a group of students:
Student[] classList = {
new Student("David", 18),
new Student("Eva", 21),
new Student("Frank", 20)
};
for (Student s : classList) {
s.displayInfo();
}
While arrays of objects are efficient, Java’s ArrayList
or other collections are often more suitable when the size needs to be flexible, or more functionality is required. However, arrays of objects are ideal when: