我们知道TreeMap可以实现Map的键元素的排序功能,但是要求键元素的类型是可比较的(Comparable),也就是键元素类型必须实现Comparable接口。
例如:
class Students {
private String sid; //学号
private String name; //姓名
private int score; //分数
public Students() {
}
public Students(String sid, String name, int score) {
this.sid = sid;
this.name = name;
this.score = score;
}
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() {
return "Students{" +
"sid='" + sid + '\'' +
", name='" + name + '\'' +
", score=" + score +
'}';
}
}
public class Test {
public static void main(String[] args) {
Map map = new TreeMap();
map.put(new Students("S001", "张三", 89), "北京市");
map.put(new Students("S002", "李四", 98), "北京市");
map.put(new Students("S003", "王五", 78), "北京市");
map.put(new Students("S004", "赵六", 90), "北京市");
Set<Map.Entry> entries = map.entrySet();
for(Map.Entry entry:entries){
System.out.println(entry.getKey() + "=" + entry.getValue());
}
}
}
运行时抛出以下异常:
Exception in thread "main" java.lang.ClassCastException: setdemo.Students cannot be cast to java.lang.Comparable
改写Students类,实现Comparable接口,按照学生的考试成绩降序排序。
class Students implements Comparable<Students> {
private String sid; //学号
private String name; //姓名
private int score; //分数
public Students() {
}
public Students(String sid, String name, int score) {
this.sid = sid;
this.name = name;
this.score = score;
}
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public int compareTo(Students s) {
return s.getScore()-this.getScore();
}
@Override
public String toString() {
return "Students{" +
"sid='" + sid + '\'' +
", name='" + name + '\'' +
", score=" + score +
'}';
}
}
public class Test {
public static void main(String[] args) {
Map map = new TreeMap();
map.put(new Students("S001", "张三", 89), "北京市");
map.put(new Students("S002", "李四", 98), "北京市");
map.put(new Students("S003", "王五", 78), "北京市");
map.put(new Students("S004", "赵六", 90), "北京市");
Set<Map.Entry> entries = map.entrySet();
for(Map.Entry entry:entries){
System.out.println(entry.getKey() + "=" + entry.getValue());
}
}
}
运行结果如下:
Students{sid='S002', name='李四', score=98}=北京市
Students{sid='S004', name='赵六', score=90}=北京市
Students{sid='S001', name='张三', score=89}=北京市
Students{sid='S003', name='王五', score=78}=北京市
==注意:不建议使用复杂的自定义对象类型作为键(例如:Students类型),通常情况下强烈建议使用String类型作为键,Object类型作为值。==