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;
}
本文来自博客园,作者:maplerain,转载请注明原文链接:https://www.cnblogs.com/maplerain/p/16672519.html 博主B站