黑马程序员技术交流社区

标题: 集合 [打印本页]

作者: lts0616    时间: 2015-12-30 19:31
标题: 集合
TreeMap<Student, String> tm = new TreeMap<>(new Comparator<Student>() {

                        @Override
                        public int compare(Student s1, Student s2) {
                                int num = s1.getAge() - s2.getAge();
                                //int num2 = num ==0? s1.getName().compareTo(s2.getName()) : num;
                                return num == 0 ? 1 : num;  //return 0; 代表所有键一样。
                                //return num;  //num 为0;即年龄相同 即键相同,不看名字了;这是自己定义的规则决定的,为什么这里不能用增强for了
                        }

                });// 导包
                        // 添加元素
                tm.put(new Student("张三丰", 25), "合肥");
                tm.put(new Student("张三丰", 25), "上海");
                tm.put(new Student("张无忌", 24), "合肥");
                tm.put(new Student("张无忌", 25), "南京");
                tm.put(new Student("张翠山", 27), "南京");
                tm.put(new Student("鲁达", 23), "上海");
                System.out.println(tm);
               
                // 遍历
                // 获取所有键
                Set<Student> set = tm.keySet();// 导包
                // 增强for
                for (Student key : set) {
                        // 获取值
                        String s2 = tm.get(key);
                        System.out.println(key + "--------------" + s2);
                }
为什么遍历后的值是null?




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2