开发者

Why don't Java LinkedHashMaps have an insert() method?

开发者 https://www.devze.com 2023-01-28 08:37 出处:网络
By insert(), I mean insertBefore(key) or insertAfter(开发者_如何学运维key). As far as I can make out, inserting a key in the middle of the map can only be achieved by creating a new map and copying a

By insert(), I mean insertBefore(key) or insertAfter(开发者_如何学运维key).

As far as I can make out, inserting a key in the middle of the map can only be achieved by creating a new map and copying across the existing keys and the new key in the correct order.

Considering that LinkedHashMaps are based on double-linked lists, it would have been trivial to implement insertBefore(key) or insertAfter(key).

Am I missing something here?

Update Thanks to everyone who pointed out the the above methods would break the contract of maintaining insertion order.

So let me rephrase the question: does anyone know of a class that would let me do this?

I looked at SortedMap (and its derivatives, including NavigableMap) but I don't want the map to be explicitly sorted. Think of a nodeList in the browser DOM. I just need to be able to insert elements (in this case KV pairs) in any arbitrary order.

Thanks


If you want an ordered map, it is intended that you use a NavigableMap


Because Map doesn't have insert() or insertFirst() or insertAfter() methods. Having said that, it is no more trivial thing to do. May be a class which doesn't belong to this hierarchy could do that.


Because:

This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

Hence this part of the contract of the class can only be maintained, if you have zero degrees of freedom as to where an element is inserted. Inserting before an(y) existing element clearly violates this part of the contract, so such an insert method would not make any sense.

(The only version that would be legal would be an insertAfter(key) where key was always the last entry in the map. And lo, that's exactly what put(key) does already.)


LinkedHashMap maintains either access-order or insertion-order. It doesn't make sense to define insertBefore(key) or insertAfter(key) I think.

0

精彩评论

暂无评论...
验证码 换一张
取 消