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 @   maplerain  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· winform 绘制太阳,地球,月球 运作规律
· 上周热点回顾(3.3-3.9)
01:26:31
2025年03月11日
本博客主要为个人学习使用,博主目前为某专科学校大二学生,能力尚有所欠缺,若发现文章中存在错误,请在评论区向博主反映,博主会第一时间进行更改或补充,感谢!
点击右上角即可分享
微信分享提示