原 自学JVAVA---(41)--(内功心法【39】)TreeSet

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 +
                '}';
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值