TreeSet:
实现了Set接口。
会给Set集合中的元素进行指定方式的排序。
底层数据结构是:二叉树(参考红黑树)。排序的第一种方式:
让元素自身具备比较性。让放入TreeSet中的元素类实现Comparable接口,覆盖compareTo方法。TreeSet会调用元素的compareTo方法排序元素。
package test;
import java.util.*;
class Hee
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet();
ts.add(new Student("lisi0",30));
ts.add(new Student("lisixx",29));
ts.add(new Student("lisi9",29));
ts.add(new Student("lisi8",38));
ts.add(new Student("lisixx",29));
ts.add(new Student("lisi4",14));
ts.add(new Student("lisi7",27));
System.out.println(ts);
}
}
//按照学生的年龄排序。
class Student implements Comparable<Student>
{
private int age;
private String name;
Student(String name,int age)
{
this.age = age;
this.name = name;
}
public int compareTo(Student stu)
{
if(this.age>stu.age)
return 1;
if(this.age==stu.age)
return this.name.compareTo(stu.name);
return -1;
}
public String toString()
{
return name+":"+age;
}
}
结果:
[lisi4:14, lisi7:27, lisi9:29, lisixx:29, lisi0:30, lisi8:38]
这时可以让集合自身具备比较性。
可以定义一个类实现Comparator接口,覆盖compare方法。将该Comparator接口子类对象作为实际参数传递给TreeSet集合构造函数。TreeSet自动根据Comparator子对象的compare方法来对集合中的对象排序。
package test;
import java.util.*;
class Hee
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet(new StudentByName());
ts.add(new Student("lisi0",30));
ts.add(new Student("lisixx",29));
ts.add(new Student("lisi9",29));
ts.add(new Student("lisi8",38));
ts.add(new Student("lisixx",29));
ts.add(new Student("lisi4",14));
ts.add(new Student("lisi7",27));
System.out.println(ts);
}
}
class Student
{
private int age;
private String name;
Student(String name,int age)
{
this.age = age;
this.name = name;
}
public String toString()
{
return name+":"+age;
}
public int getAge()
{
return age;
}
public String getName()
{
return name;
}}
class StudentByName implements Comparator<Student>
{
public int compare(Student s1,Student s2)
{
int num = new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
return num==0 ? s1.getName().compareTo(s2.getName()):num;
}
}
结果:
[lisi4:14, lisi7:27, lisi9:29, lisixx:29, lisi0:30, lisi8:38]
总结:
单点解释吧:用自定义类实现Comparable接口,那么这个类就具有排序功能,Comparable和具体你要进行排序的类的实例邦定。而Comparator比较灵活,只需要通过构造方法指定一个比较器就行了实现它的自定义类仅仅定义了一种排序方式或排序规则。不言而喻,这种方式比较灵活。我们的要排序的类可以分别和多个实现Comparator接口的类绑定,从而达到可以按自己的意愿实现按多种方式排序的目的。Comparable——“静态绑定排序”,Comparator——“动态绑定排序”。