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站
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· winform 绘制太阳,地球,月球 运作规律
· 上周热点回顾(3.3-3.9)