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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 郭孟涛 高级黑马   /  2013-2-8 04:44  /  1170 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

TreeSet不是直接就可以对数据进行排序,为什么要重写Comparator来再次排一遍呢?{:3_46:}

题目:对学生成绩用TreeSet和Comparator实现排序

TreeSet默认直接排序是用的Comparator还是comparable方法呢?

2 个回复

正序浏览
因为TreeSet的二叉树结构,所以他接收的元素必须要有比较性,下面是我学习时总结的,你可以详细看下

TreeSet存储自定义对象
        |-- 示例:往TreeSet集合中存储自定义对象学生,按照学生的年龄进行排序。
        |-- 问题:当存储第二个元素时出现异常,因为TreeSet集合存储元素时需要按照一定顺序。
        |-- 解决方法1:让元素自身具备比较性,让学生类实现Comparable接口,覆盖compareTo方法。
        |-- 解决方法2:让Treeset集合具备比较性,定义Comparator比较器,将比较器对象作为参数传递给TreeSet集合的构造函数。
        |-- 比较器如何定义:定义一个类,实现Comparator接口,覆盖compare方法。
        |-- 区别:当两种方法都存在时,以比较器为主。比较器较常用些。
        方法1:
        class Student implements Comparable//该接口强制让学生具备比较性
        {
                private String name;
                private int age;
                Student(String name,int age)
                {
                        this.name = name;
                        this.age = age;
                }
                public int compareTo(Object obj)
                {
                        if(!(obj instanceof Student))
                                throw new RuntimeException("不是学生对象");
                        Student s = (Student)obj;
                        if(this.age > s.age)
                                return 1;
                        if(this.age == s.age)
                        {
                                this.name.compareTo(s.name);       
                        }                       
                        return -1;
                }
        }
        方法2:
        Treeset ts = newTreeSet(new MyCompare());
        class MyCompare implements Comparator
        {
                public int compare(Object o1,Object o2)
                {
                        Student s1 = (Student)o1;
                        Student s2 = (Student)o2;
                        int num = s1.getName().compareTo(s2.getName());
                        if (num == 0)
                        {
                                //return s1.getAge() - s2.getAge();
                                return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
                        }
                        return num;
                }
        }

评分

参与人数 1技术分 +1 收起 理由
Rancho_Gump + 1

查看全部评分

回复 使用道具 举报
TreeSet使用定制排序或者自然排序。
因为要排序,所以元素要有可比性,于是就是使元素实现comparable接口,复写compareTo方法。
这个方法,定义了怎么样的元素是“较大”,什么元素“较小”,所以可以排序。

comparator接口是用在TreeSet 初始化时,,传给他的构造函数。


如果两个都有了,那么Comparator的会使用,comparable就不会使用

评分

参与人数 1技术分 +1 收起 理由
Rancho_Gump + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马