Java Object Arrays: Definition and Usage
In Java, you can define and use object arrays through the following methods:
- Define an array of objects.
// 定义一个长度为5的Person对象数组
Person[] persons = new Person[5];
// 初始化对象数组
persons[0] = new Person("Alice", 25);
persons[1] = new Person("Bob", 30);
//...
- Iterate through the array of objects.
for (int i = 0; i < persons.length; i++) {
System.out.println(persons[i].getName() + " is " + persons[i].getAge() + " years old");
}
- Methods and properties that use arrays as parameters.
// 获取对象数组中某个对象的属性
String name = persons[0].getName();
int age = persons[0].getAge();
// 调用对象数组中某个对象的方法
persons[0].sayHello();
By using the above methods, you can define and use arrays of objects to manipulate and access objects within the array.