TreeMap: NavigableMap<K,V> subMap(),它是否创建了新的地图对象?

TreeMap: NavigableMap<K,V> subMap (), does it creates new map object?

public NavigableMap<K,V> subMap(K fromKey,
                       boolean fromInclusive,
                       K toKey,
                       boolean toInclusive)

Description copied from interface: NavigableMap Returns a view of the portion of this map whose keys range from fromKey to toKey. If fromKey and toKey are equal, the returned map is empty unless fromInclusive and toInclusive are both true. The returned map is backed by this map, so changes in the returned map are reflected in this map, and vice-versa. The returned map supports all optional map operations that this map supports.

这个函数是否创建新的地图对象? return 对象中存储了什么?

Does this function create new map object?

是的,但是这个 Map 对象没有映射中包含键和值的节点的新副本。如果更改底层地图,它可以更改此地图。

是的,它创建了一个新地图实例,但新地图中的对象引用了旧地图中的对象。 因此,两个地图中存在的对象的所有修改在两个地图上都是可见的,因为对象是相同的。

请注意,即使它是一个新实例 Map。它不是 classic 全功能地图实例。不能添加新元素,只能替换或移除subMap范围内的元素。

编辑

The returned map will throw an IllegalArgumentException on an attempt to insert a key outside of its range, or to construct a submap either of whose endpoints lie outside its range.

例如在包static class NavigableSubMap of the JDK 1.6 :

public final V put(K key, V value) {
            if (!inRange(key))
                throw new IllegalArgumentException("key out of range");
            return m.put(key, value);
}


public final V remove(Object key) {
        return !inRange(key) ? null : m.remove(key);
}

通常考虑并使用子地图作为子集合(例如子列表也是)作为原始地图的视图范围限制是一个很好的做法。