黑马程序员技术交流社区
标题:
为什么要重写Comparator来再次排一遍
[打印本页]
作者:
郭孟涛
时间:
2013-2-8 04:44
标题:
为什么要重写Comparator来再次排一遍
TreeSet不是直接就可以对数据进行排序,为什么要重写Comparator来再次排一遍呢?{:3_46:}
题目:对学生成绩用TreeSet和Comparator实现排序
TreeSet默认直接排序是用的Comparator还是comparable方法呢?
作者:
罗海清
时间:
2013-2-8 08:27
TreeSet使用定制排序或者自然排序。
因为要排序,所以元素要有可比性,于是就是使元素实现comparable接口,复写compareTo方法。
这个方法,定义了怎么样的元素是“较大”,什么元素“较小”,所以可以排序。
comparator接口是用在TreeSet 初始化时,,传给他的构造函数。
如果两个都有了,那么Comparator的会使用,comparable就不会使用
作者:
郭冰川
时间:
2013-2-8 09:23
因为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;
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2