TreeSet類(lèi)內(nèi)部采用的二叉樹(shù)數(shù)據(jù)結(jié)構(gòu),默認(rèn)使用元素的自然排序接口Comparable對(duì)元素進(jìn)行排序,也可以在構(gòu)造時(shí)指定排序器Comparator來(lái)指定排序規(guī)則。
例如若將自定義Student類(lèi)的對(duì)象放置到TreeSet中,按照姓名字典順序排序,可以采用兩種方式實(shí)現(xiàn)。
讓Student類(lèi)實(shí)現(xiàn)Comparable接口,重寫(xiě)compareTo(Student)方法,在方法定義排序規(guī)則。
定義排序器類(lèi)實(shí)現(xiàn)Comparator接口,重寫(xiě)compare(Student s1,Student s2)方法,在方法定義排序規(guī)則,在構(gòu)造TreeSet實(shí)例時(shí)傳入排序器類(lèi)實(shí)例。。
示例:
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);
}
}
}