Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinkedHashMap in .NET

Tags:

I wonder if there is a counterpart to java.util.LinkedHashMap in .NET? (ie. the elements are (re)ordered automatically if I access an element. (boolean accessOrder) ).

like image 560
Schildmeijer Avatar asked Jan 28 '09 08:01

Schildmeijer


People also ask

What is LinkedHashMap used for?

Answer: The main use of LinkedHashMap in Java is to use it for preserving the insertion order. It can also be used to preserve the access order using which the keys are accessed.

What is difference between LinkedHashMap and HashMap?

Difference Between LinkedHashMap and HashMap The Major Difference between the HashMap and LinkedHashMap is the ordering of the elements. The LinkedHashMap provides a way to order and trace the elements. Comparatively, the HashMap does not support the ordering of the elements.

What is LinkedHashMap in data structures?

LinkedHashMap is the data structure used to store the key-value pairs like HashMap but it guarantees the order of insertion(unlike the HashMap). So the elements are stored in the order of their insertion.

How does a LinkedHashMap work?

LinkedHashMap extends HashMap class and implements Map interface. That means LinkedHashMap has all functionality same as the HashMap either calculating index using Hashing for bucket finding. The difference between LinkedHashMap and HashMap is the LinkedHashMap has retrieval order same as insertion order.


1 Answers

Just to clarify a bit for readers: LinkedHashMap only behaves that way when built with one particular constructor overload. Normally the elements are maintained in insert order. (This feels a little odd to me, but never mind.)

I don't believe there's any such class in .NET. It wouldn't be too hard to build one, using a linked list of elements and a dictionary from key to linked list node. Access would then consist of fetching the linked list node, moving it to the head, and returning the value.

I'd be happy to implement it tonight or tomorrow if you want - although probably not with full unit tests etc. (Fully testing a collection is a time-consuming business!)

like image 60
Jon Skeet Avatar answered Oct 07 '22 01:10

Jon Skeet