📅  最后修改于: 2023-12-03 15:23:24.446000             🧑  作者: Mango
在Java中,我们可以使用TreeMap来实现按照键值排序的Map接口。而当我们使用自定义的类对象来作为键或值时,我们需要实现Comparable接口并重写compareTo方法来定义排序规则。接下来我们将介绍如何在Java中打印具有自定义类对象作为键或值的TreeMap。
public class Student implements Comparable<Student> {
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
@Override
public int compareTo(Student o) {
return this.id - o.id;
}
}
// 创建TreeMap对象并添加自定义类对象作为键
TreeMap<Student, Integer> studentScores = new TreeMap<Student, Integer>();
studentScores.put(new Student(1, "John"), 90);
studentScores.put(new Student(2, "Mary"), 85);
studentScores.put(new Student(3, "Alex"), 95);
// 创建TreeMap对象并添加自定义类对象作为值
TreeMap<Integer, Student> studentInfo = new TreeMap<Integer, Student>();
studentInfo.put(1, new Student(1, "John"));
studentInfo.put(2, new Student(2, "Mary"));
studentInfo.put(3, new Student(3, "Alex"));
// 遍历TreeMap并打印自定义类对象作为键和值
// 首先遍历studentScores
for (Map.Entry<Student, Integer> entry : studentScores.entrySet()) {
System.out.println(entry.getKey().getId() + " " + entry.getKey().getName() + " - " + entry.getValue());
}
// 然后遍历studentInfo
for (Map.Entry<Integer, Student> entry : studentInfo.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue().getId() + " " + entry.getValue().getName());
}
运行上述代码将得到以下结果:
1 John - 90
2 Mary - 85
3 Alex - 95
1 - 1 John
2 - 2 Mary
3 - 3 Alex
其中第一行到第三行是遍历studentScores的结果,第四行到第六行是遍历studentInfo的结果。
在Java中打印具有自定义类对象作为键或值的TreeMap需要我们实现Comparable接口并重写compareTo方法来定义排序规则。然后,我们可以像操作普通的TreeMap一样添加、删除、修改,并且遍历其中的数据进行操作。