java - Java:从 HashMap 打印内容
问题描述
我需要打印HashMap<String, StudentSchedule>
StudentSchedule 是存储其他对象的类的所有内容。在 StudentSchedule 中,有一个函数可以打印出一些我希望它在打印 HashMap 时打印的数据。我已经使用增强的 for 循环来打印 HashMap,但是值就像对象编号。当值正在打印时,我希望它打印 StudentSchedule.printSchedule() 中的函数。我不确定这是否可能。我想我已经让它变得更复杂了,但这是我到目前为止所拥有的:
public class StudentSchedule {
private Student student;
private Course course;
private String[] courseDays;
private String[] courseTimes;
public StudentSchedule(Student student, Course course, String[] courseDays, String[] courseTimes) {
this.student = student;
this.course = course;
this.courseDays = courseDays;
this.courseTimes = courseTimes;
}
public Student getStudent() {
return student;
}
public Course getCourse() {
return course;
}
public String[] getCourseDays() {
return courseDays;
}
public String[] getCourseTimes() {
return courseTimes;
}
public void printSchedule() {
System.out.println("\nClass Schedule");
String studentInfo = getStudent().toString();
String courseInfo = getCourse().toString();
String[] courseDays = getCourseDays();
String[] courseTimes = getCourseTimes();
if(courseDays[2] != null && courseTimes[2] != null) {
System.out.println(studentInfo + "\n" + courseInfo + "\n" +
courseDays[0] + " -> " + courseTimes[0] + "\n" +
courseDays[1] + " -> " + courseTimes[1] + "\n" +
courseDays[2] + " -> " + courseTimes[2]);
}
else {
System.out.println(studentInfo + "\n" + courseInfo + "\n" +
courseDays[0] + " -> " + courseTimes[0] + "\n" +
courseDays[1] + " -> " + courseTimes[1]);
}
}
}
调度管理器
public class ScheduleManager
{
private HashMap<String, StudentSchedule> allStudentSchedule = new HashMap<>();
public void createSchedule() {
Student newStudent = getStudentInfo();
Course newCourse = getCourseInfo();
courseDays = getCourseDays();
courseTimes = getCourseTimes(courseDays);
studentSchedule = new StudentSchedule(newStudent, newCourse, courseDays, courseTimes);
allStudentSchedule.put(newStudent.getStudentId(), studentSchedule);
// testing print schedule
studentSchedule.printSchedule();
}
private void displaySchedule() {
Set<Entry<String,StudentSchedule>> hashSet = allStudentSchedule.entrySet();
for(Entry entry : hashSet ) {
System.out.println("Key="+entry.getKey()+", Value="+entry.getValue());
}
}
....
解决方案
覆盖toString
StudentSchedule 类的方法并在其中调用 printSchedule。像这样的东西
@Override
public String toString() {
printSchedule();
return "";
}
推荐阅读
- reactjs - 需要在 React Redux Reducer 状态下运行 .slice
- email - 使用不同 DNS 回复邮件时的 URL 转发
- java - Java:使用 FileHandler 进行日志记录、轮换
- corda - 是否可以使用 Oracle Wallet 将节点连接到其保管库?
- docker - Docker-compose 标记和推送
- html - 在不更改子标签 CSS 的情况下防止子标签宽度
- javascript - 如何将reducer case函数更改为不可变js
- php - 如果我将 shell_exec 用于需要密码的命令该怎么办
- python - Python - Ctypes CFUNCTYPE 在 ARM 设备中崩溃
- google-cloud-platform - 是否可以使用内部 IP 创建 GKE 入口控制器?