class test15 {
public static void main(String[] args) {
SortedSet<item> aSet = new TreeSet<item>();
aSet.add(new item("GodV",13));
aSet.add(new item("mifengaaa",30));
aSet.add(new item("Aluka",123));
aSet.add(new item("Cpt",33));
aSet.add(new item("GodV",42));
System.out.println(aSet);
NavigableSet<item> bSet = new TreeSet<>(
Comparator.comparingInt(p->p.getNumber())
);
// 像下面这样写也可以:
// NavigableSet<item> bSet = new TreeSet<>(
// Comparator.comparingInt(item::getNumber)
// );
bSet.addAll(aSet);
System.out.println(bSet);
}
}
class item implements Comparable<item>{
private int number;
private String description;
public item(){}
public item(String description, int number){
this.number = number;
this.description = description;
}
public int getNumber(){
return this.number;
}
public String getDescription(){
return this.description;
}
@Override
public int compareTo(item u){
return this.description.compareTo(u.getDescription())==0?Integer.compare(this.number, u.getNumber()):this.description.compareTo(u.getDescription());
}
@Override
public String toString(){
return this.description+"-"+this.number;
}
}
TreeSet<item> a = new TreeSet<>();
Class<?> cl = a.getClass();
Constructor<?>[] methods = cl.getDeclaredConstructors();
for(Constructor<?> i : methods) System.out.println(i);
1
2
3
4
发现有下面几种构造器:
public java.util.TreeSet(java.util.SortedSet)
public java.util.TreeSet(java.util.Collection)
public java.util.TreeSet(java.util.Comparator)
public java.util.TreeSet()
java.util.TreeSet(java.util.NavigableMap)
1
2
3
4
5
所以也可以使用lambda表达式或者使用method reference传入一个Comparator来实现排序的指定, 这样就不会默认去调用自己的compareTo方法了;
也可以传入一个SortedSet或者Collection来Copy所有的内容;
最后上一些树集常用的方法: