Java怎样用数组保存对象
时间: 2023-05-28 18:04:31 浏览: 97
Java中使用数组保存对象的步骤如下:
1. 定义对象类,例如:
```java
public class Student {
private String name;
private int age;
// 构造方法
public Student(String name, int age) {
this.name = name;
this.age = age;
}
// getter和setter方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// 其他方法
public void study() {
System.out.println(name + "正在学习");
}
}
```
2. 创建对象数组,例如:
```java
Student[] students = new Student[3];
```
3. 初始化数组元素,例如:
```java
students[0] = new Student("张三", 20);
students[1] = new Student("李四", 21);
students[2] = new Student("王五", 22);
```
4. 访问数组元素,例如:
```java
students[0].study(); // 输出:张三正在学习
```
5. 遍历数组,例如:
```java
for (int i = 0; i < students.length; i++) {
System.out.println(students[i].getName() + "的年龄是" + students[i].getAge());
}
```
输出:
```
张三的年龄是20
李四的年龄是21
王五的年龄是22
```
阅读全文