Java TreeSet subSet方法源码解析

// TreeSet类
public NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
                              E toElement,   boolean toInclusive) {

    return new TreeSet<>(m.subMap(fromElement, fromInclusive, // 返回TreeSet对象,这里的m是TreeMap的实例,由TreeSet无参构造进行创建的
                                   toElement,   toInclusive));
}

// TreeMap类
public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, // 表示闭区间[fromKey,toKey]
                                K toKey,   boolean toInclusive) {
    return new AscendingSubMap<>(this, // new一个AscendingSubMap实例,this作为参数与区间一并传入,这里的this指向上述的m
                                 false, fromKey, fromInclusive,
                                 false, toKey,   toInclusive);
}

// TreeMap类-内部类AscendingSubMap
AscendingSubMap(TreeMap<K,V> m,
                boolean fromStart, K lo, boolean loInclusive,
                boolean toEnd,     K hi, boolean hiInclusive) {
    super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); // 向父类构造器传入对象m与区间
}

NavigableSubMap(TreeMap<K,V> m,
                boolean fromStart, K lo, boolean loInclusive,
                boolean toEnd,     K hi, boolean hiInclusive) {
    if (!fromStart && !toEnd) {
        if (m.compare(lo, hi) > 0) // 判断lower是否大于higher,如果是则抛出错误
            throw new IllegalArgumentException("fromKey > toKey");
    } else {
        if (!fromStart) // type check 类型检查,不知道fromStart是干啥的,正常流程不会走这里,我猜测是靠调用compare来报错
            m.compare(lo, lo);
        if (!toEnd)
            m.compare(hi, hi);
    }

    this.m = m;
    this.fromStart = fromStart;
    this.lo = lo;
    this.loInclusive = loInclusive;
    this.toEnd = toEnd;
    this.hi = hi;
    this.hiInclusive = hiInclusive;
}
posted @ 2022-09-09 13:38  maplerain  阅读(27)  评论(0编辑  收藏  举报