定义三个教师对象,添加到集合ArryList,遍历输出
时间: 2023-07-06 17:39:31 浏览: 111
任务九:使用集合ArryList集合对类对象Member和Goods类的形势完成淘宝shopping”购物管理系统购物结算模块和客户管理模块
好的,以下是一个示例代码,用于定义三个教师对象,添加到 ArrayList 集合中,并进行遍历输出:
```java
import java.util.ArrayList;
public class Teacher {
private String name;
private int age;
private String subject;
public Teacher(String name, int age, String subject) {
this.name = name;
this.age = age;
this.subject = subject;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getSubject() {
return subject;
}
public static void main(String[] args) {
// 创建 ArrayList 对象
ArrayList<Teacher> teachers = new ArrayList<>();
// 定义三个 Teacher 对象
Teacher teacher1 = new Teacher("张三", 35, "数学");
Teacher teacher2 = new Teacher("李四", 40, "英语");
Teacher teacher3 = new Teacher("王五", 30, "物理");
// 将三个 Teacher 对象添加到 ArrayList 中
teachers.add(teacher1);
teachers.add(teacher2);
teachers.add(teacher3);
// 遍历 ArrayList,输出每个 Teacher 对象的信息
for (Teacher teacher : teachers) {
System.out.println("姓名:" + teacher.getName() + ",年龄:" + teacher.getAge() + ",科目:" + teacher.getSubject());
}
}
}
```
运行以上代码,将会输出以下结果:
```
姓名:张三,年龄:35,科目:数学
姓名:李四,年龄:40,科目:英语
姓名:王五,年龄:30,科目:物理
```
阅读全文