对于那些手头有源代码的问题非常有用,因为有了足够的 IDE 支持,您可以简单地浏览实现。查看TreeMap的源码可以看出,这三个方法都使用constructor of AscendingSubMap构造了一个新的地图:
public NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
K toKey, boolean toInclusive) {
return new AscendingSubMap(this,
false, fromKey, fromInclusive,
false, toKey, toInclusive);
}
除了通过超级构造函数将参数传递给NavigableSubMap类之外什么都不做:
super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
所以这三个方法都是基于下面的构造函数:
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)
throw new IllegalArgumentException("fromKey > toKey");
} else {
if (!fromStart) // type check
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;
}
出于类型和断言检查的原因,我在这里看到的只是对compare 的调用。因此,它应该是 O(1)。
您始终可以browse the source code online,但我真的建议您获取源文件并将它们链接到您选择的 IDE。