import java.util.*;
/*
TreeSet集合內部實現了排序
1. 自定義對象需要實現Comparable接口的compareTo方法,自定義排序規則,return 1(第一個元素大於第二個元素),0(相等),-1(小於)
【正數負數均可,不一定要是1或者-1】
2. 如果元素本身的排序規則不適用,那麼自定義比較器實現Comparator接口,並在初始化集合的時傳入。
3. 底層數據結構是二叉樹,大於放右邊,小於放左邊
*/
class TreeSetDemo {
public static void main(String[] args) {
TreeSet ts = new TreeSet(new Mycompare());
// ts.add(new People("張三",3));
// ts.add(new People("趙一",9));
// ts.add(new People("李四",4));
// ts.add(new People("王五",5));
// ts.add(new People("李四四",4));
ts.add(new People("a02",3));
ts.add(new People("a01",5));
ts.add(new People("a39",9));
ts.add(new People("a40",7));
System.out.println(ts);
Iterator i = ts.iterator();
while(i.hasNext()) {
People p = (People) i.next();
System.out.println(p.getName() + "....." + p.getAge());
}
}
}
// 元素類實現Comparable接口,複寫compareTo方法
class People implements Comparable {
private String name;
private int age;
People (String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge(){
return this.age;
}
public int compareTo (Object obj) {
People p = (People) obj;
if (this.age > p.age) {
return 1;
} else if (this.age == p.age){
return this.name.compareTo(p.name);
}
return -1;
}
}
// 比較器實現Comparator接口,複寫compare方法
class Mycompare implements Comparator {
public int compare(Object o1, Object o2) {
People p1 = (People) o1;
People p2 = (People) o2;
int num = p1.getName().compareTo(p2.getName());
if (num == 0) {
return p1.getAge() - p2.getAge();
}
return num;
}
}
TreeSet集合內部排序
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.