自定义 Teacher类(教工号、姓名、所授课程、教学()) 要求一:定义三个教师对象,添加到集合(ArrayList),遍历输出。 要求二:定义Map集合,用Teacher对象为key,教师电话(字符串)为value,遍历Map集合。
时间: 2024-04-23 08:25:03 浏览: 143
好的,下面是一个示例代码,其中定义了一个Teacher类,并实现了要求一和要求二的功能:
```
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// 要求一:定义三个教师对象,添加到集合(ArrayList),遍历输出。
ArrayList<Teacher> teacherList = new ArrayList<>();
teacherList.add(new Teacher("001", "张三", "数学"));
teacherList.add(new Teacher("002", "李四", "语文"));
teacherList.add(new Teacher("003", "王五", "英语"));
for (Teacher teacher : teacherList) {
System.out.println("教工号:" + teacher.getId());
System.out.println("姓名:" + teacher.getName());
System.out.println("所授课程:" + teacher.getCourse());
teacher.teach();
System.out.println("=====================");
}
// 要求二:定义Map集合,用Teacher对象为key,教师电话(字符串)为value,遍历Map集合。
Map<Teacher, String> teacherPhoneMap = new HashMap<>();
teacherPhoneMap.put(new Teacher("001", "张三", "数学"), "13888888888");
teacherPhoneMap.put(new Teacher("002", "李四", "语文"), "13999999999");
teacherPhoneMap.put(new Teacher("003", "王五", "英语"), "13111111111");
for (Map.Entry<Teacher, String> entry : teacherPhoneMap.entrySet()) {
Teacher teacher = entry.getKey();
String phone = entry.getValue();
System.out.println("教工号:" + teacher.getId());
System.out.println("姓名:" + teacher.getName());
System.out.println("所授课程:" + teacher.getCourse());
System.out.println("电话:" + phone);
System.out.println("=====================");
}
}
}
class Teacher {
private String id;
private String name;
private String course;
public Teacher(String id, String name, String course) {
this.id = id;
this.name = name;
this.course = course;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getCourse() {
return course;
}
public void teach() {
System.out.println("正在教授" + course + "课程");
}
// 重写hashCode和equals方法,用于Map集合中的比较
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Teacher teacher = (Teacher) obj;
return id.equals(teacher.id);
}
}
```
上面的代码定义了一个Teacher类,包含教工号、姓名、所授课程等属性,以及teach()方法用于输出教学信息。在要求一中,我们创建了一个ArrayList集合,向其中添加了三个Teacher对象,并使用for-each循环遍历输出每个教师的信息。在要求二中,我们创建了一个Map集合,将Teacher对象作为key,教师电话作为value,并使用for-each循环遍历输出每个教师以及其电话信息。
希望这个示例代码能够帮助你!
阅读全文