A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© lnz_黑仔 中级黑马   /  2015-1-11 17:37  /  581 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

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的张三给删除了,保留后面的删除前面重复的
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马