//綜合案例:集合TreeSet==>自帶排序的集合
public class Event_TreeSet {
public static void main(String[] ags) {
//TreeSet中有一個方法:public TreeSet(Comparator<? super E> comparator) {this(new TreeMap<>(comparator));},
//但是這個方法需要一個Comparator作為參數,而這個參數Comparator又是一個函數式接口,int compare(T o1, T o2); so 你懂得!
//第一種:
//Set<Person> personSet=new TreeSet<>((ele1,ele2)-> ele1.getAge()-ele2.getAge());
//第二種:這兩種隻是不同的實作方式而已
Set<Person> personSet=new TreeSet<>((ele1,ele2)->{
if(ele1.getAge()>ele2.getAge()) {
return 1;
}else {
return -1;
}
});
personSet.add(new Person("Lily",10));
personSet.add(new Person("Poliy",20));
personSet.add(new Person("LiHui",15));
personSet.add(new Person("Lucy",13));
//直接列印的話:抛異常:Person cannot be cast to java.lang.Comparable
//多個person進行對比 不知道哪個person大 哪個小 無法直接對比
System.out.println(personSet);
//輸出:
//[Person [name=Lily, age=10], Person [name=Lucy, age=13], Person [name=LiHui, age=15], Person [name=Poliy, age=20]]
}
}