import java.util.Comparator;
import java.util.Set;
import java.util.TreeMap;
//创建一个TreeMap,存储5对元素,字符串做为键,Student做为值.然后遍历集合.
//完成需求并思考,如果使用TreeMap集合存储学生对象,并且想去除其中的重复元素,该怎么做?
public class TreeMapDemo {
public static void main(String[] args) {
TreeMap<StudentTree, String> tm = new TreeMap<StudentTree, String>(
new Comparator<StudentTree>() {
public int compare(StudentTree stu1, StudentTree stu2) {
int num1 = stu1.getAge() - stu2.getAge();
int num2 = (num1 == 0) ? stu1.getName().compareTo(
stu2.getName()) : num1;
return num2;
}
});
StudentTree s1 = new StudentTree("张三", 20);
StudentTree s2 = new StudentTree("李四", 21);
StudentTree s3 = new StudentTree("王八", 22);
StudentTree s4 = new StudentTree("张三", 20);
StudentTree s5 = new StudentTree("张三", 21);
tm.put(s1, "1");//需要保留唯一的元素放到前面去
tm.put(s2, "2");
tm.put(s3, "3");
tm.put(s4, "4");
tm.put(s5, "5");
Set<StudentTree> key = tm.keySet();
for (StudentTree stu : key) {
String str = tm.get(stu);
System.out.println(str + stu.getName() + stu.getAge());// ClassCastException:类型转换异常
}//1的张三给删除了,保留后面的删除前面重复的
}
}
|
|