TreeSet类内部采用的二叉树数据结构,默认使用元素的自然排序接口Comparable对元素进行排序,也可以在构造时指定排序器Comparator来指定排序规则。
例如若将自定义Student类的对象放置到TreeSet中,按照姓名字典顺序排序,可以采用两种方式实现。
让Student类实现Comparable接口,重写compareTo(Student)方法,在方法定义排序规则。
定义排序器类实现Comparator接口,重写compare(Student s1,Student s2)方法,在方法定义排序规则,在构造TreeSet实例时传入排序器类实例。。
示例:
class Student implements Comparable{
private String name;
private int age;
private double score;
public Student(String name, int age, double score) {
super();
this.name = name;
this.age = age;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
@Override
public int compareTo(Student s) {
return 0;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", score=" + score + "]";
}
}
class StudentScoreComparator implements Comparator{
@Override
public int compare(Student s1, Student s2) {
return (int)(s1.getScore()*100-s2.getScore()*100)/100;
}
}
public class Test {
public static void main(String[] args) {
Set set=new HashSet();
set.add("Tom");
set.add("Alice");
set.add("Martin");
set.add("Jerry");
Iterator it=set.iterator();
while(it.hasNext()){
String city=it.next();
System.out.println(city);
}
}
}