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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With