TreeSet
一颗键值哈希树,只有前键做仓库。
比较顺序有内幕,排序接口来指路。
TreeSet底层是TreeMap
public class TreeSet<E> extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, java.io.Serializable
{
/**
* The backing map.
*/
private transient NavigableMap<E,Object> m;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
/**
* Constructs a set backed by the specified navigable map.
*/
TreeSet(NavigableMap<E,Object> m) {
this.m = m;
}
TreeSet测试
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<People> ps = new TreeSet<>();
ps.add(new People(1,"亚历山大",40,30000));
ps.add(new People(3,"奥巴马",32,30000));
ps.add(new People(7,"安倍晋三",44,30000));
ps.add(new People(2,"马克龙",21,300));
ps.add(new People(5,"罗斯福",55,7000));
//TreeSet是根据compareTo方法判断两个元素是大于还是小于 来排序
// 如果相等就就会取第一个元素后边的不要
ps.add(new People(3,"马相伯1",12,80000));
ps.add(new People(3,"马相伯2",12,80000));
ps.add(new People(3,"马相伯3",12,80000));
System.out.println(ps);
}
}
class People implements Comparable<People>{
private Integer id;
private String name;
private Integer age;
private Integer salary;
public People(Integer id, String name, Integer age, Integer salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
@Override
public int compareTo(People o) {
if(this.age > o.age){
return 1;
}else if(this.age < o.age){
return -1;
}else if(this.id > o.id){
return 1;
}else if(this.id < o.id){
return -1;
}if(this.id == o.id){
//TreeSet是根据compareTo方法判断两个元素是大于还是小于 来排序
// 如果相等就就会取第一个元素后边的不要
System.out.println("相等");
return 0;
}
return 0;
}
@Override
public String toString() {
return "People{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
'}';
}
}