Search code examples
javadictionarytreemaplinkedhashmapordereddictionary

Should I use LinkedHashMap or TreeMap if I insert and access in order?


If i put and iterate in natural order, should I use LinkedHashMap or TreeMap?

I will use a Map<int, MyObj>, and I will put them in natural order (1,2,3,...). I know about their big-O time performances, but I also know that this is a borderline use.


Solution

  • Use a TreeMap. Not for any performance reasons, but because it can be assigned to SortedMap (or NavigableMap), and that communicates clearly your intent that the map has a defined order.