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

By insert() , I mean insertBefore(key) or insertAfter(key) .

As far as I can figure out, inserting a key in the middle of a card can only be achieved by creating a new card and copying it through existing keys and a new key in the correct order.

Given that LinkedHashMaps are based on double lists, it would be trivial to implement insertBefore(key) or insertAfter(key) .

Did I miss something?

Update Thanks to everyone who indicated that the above methods would violate the contract to maintain the insertion order.

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

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

thanks

+4
source share
4 answers

If you want an ordered map, it is assumed that you are using NavigableMap

+4
source

Because Map does not have insert() or insertFirst() or insertAfter() . Having said that, this is no more trivial thing. Maybe a class that does not belong to this hierarchy can do this.

+3
source

LinkedHashMap supports either access order or insertion order . I think it makes no sense to define insertBefore(key) or insertAfter(key) .

+3
source

Because:

This linked list defines the iteration order, which is usually the order in which keys were inserted into the map (insert order).

Therefore, this part of the class contract can only be supported if you have zero degrees of freedom as to where the element is inserted. Inserting in front of an existing element (y) clearly violates this part of the contract, so such an insert method does not make sense.

(The only version that would be legal would be insertAfter(key) , where key always the last entry on the map. And now, this is exactly what put(key) already.)

+3
source

All Articles