手撕TreeSet底层源码

public interface SortedMap<K,V> extends Map<K,V> {
}

public interface NavigableMap<K,V> extends SortedMap<K,V> {
}

public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>{
    
    //外置比较器
    private final Comparator<? super K> comparator;
    //元素个数
    private transient int size = 0;
    //操作数
    private transient int modCount = 0;
    
    public TreeMap() {
        comparator = null;//外置比较器设置为null
    }
    
    public TreeMap(Comparator<? super K> comparator) {
        this.comparator = comparator;//赋值外置比较器
    }
    
    public V put(K key, V value) {
        //获取外置比较器
        Comparator<? super K> cpr = comparator;
        //判断是否有外置比较器
        if (cpr != null) {//说明有外置比较器
            //使用外置比较器的排序规则
        }else {//说明没有外置比较器
            
            //使用内置比较器的排序规则
        }
        size++;
        modCount++;
        return null;
    }
}
public interface SortedSet<E> extends Set<E> {
}

public interface NavigableSet<E> extends SortedSet<E> {
}

public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>{
    
    private transient NavigableMap<E,Object> m;
    
    //外界使用无参构造创建TreeSet时,底层是使用无参构造创建的TreeMap
    public TreeSet() {
        this(new TreeMap<E,Object>());
    }
    
    //外界使用有参构造创建TreeSet时,底层是使用有参构造创建的TreeMap,并把外置比较器传入到TreeMap的内部
    public TreeSet(Comparator<? super E> comparator) {
        this(new TreeMap<>(comparator));
    }

    
    TreeSet(NavigableMap<E,Object> m) {
        this.m = m;
    }
    
    //占位符
    private static final Object PRESENT = new Object();
    
    //TreeSet添加元素时,是使用到的TreeMap的put方法,并将元素存入Key中,value使用占位符占位
    public boolean add(E e) {
        return m.put(e, PRESENT)==null;
    }
}

TreeSet<Student> set = new TreeSet<>();

TreeSet<Student> set = new TreeSet<>(new Comparator<Student>() {
    @Override
    public int compare(Student o1, Student o2) {
        ......
        return 1;
    }
});

set.add(new Student("天海翼", '女', 28, "2204", "001"));
set.add(new Student("天使萌", '女', 21, "2204", "002"));
set.add(new Student("水菜丽", '女', 25, "2204", "003"));

TreeSet底层由TreeMap实现

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值