Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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

like image 843
David Semeria Avatar asked Dec 12 '22 17:12

David Semeria


2 Answers

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

like image 63
Peter Lawrey Avatar answered Dec 25 '22 06:12

Peter Lawrey


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.

like image 21
Adeel Ansari Avatar answered Dec 25 '22 06:12

Adeel Ansari