本帖最后由 JinnyZh 于 2013-5-17 22:41 编辑
import java.util.Map;
import java.util.TreeMap;
public class TreeMapDemo {
public static void main(String[] args) {
Map<Student, Integer> map = new TreeMap<>();
map.put(new Student(2,"JinnyNg"), 77);
map.put(new Student(1,"JinnyZh"), 33);
map.put(new Student(4,"Jade"), 55);
map.put(new Student(6,"Jinny"), 66);
map.put(new Student(5,"Jolin"), 78);
map.put(new Student(3,"JinnyNg"), 90);
map.put(new Student(3,"JinnyNg"), 88);
System.out.println(map);
}
}
//
class Student implements Comparable<Student> {
private int num;
private String name;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// 创建构造函数
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(int num, String name) {
super();
this.num = num;
this.name = name;
}
// 重写toString方法
@Override
public String toString() {
// 按照学号的顺序
return "学号" + num + "-" + name;
}
@Override
public int compareTo(Student o) {
// TODO Auto-generated method stub
return this.num - o.num;
}
}
不知道代码有没有复制错误,在HashMap中需要重写hashcode 和equals 方法才能去重复
但是在TreeMap中我什么都没写,他还是自动去重复了啊,什么原因?
|