'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.
Can someone help me? Thanks
Solution 1:[1]
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.
Solution 2:[2]
- If you want to keep the entries in the order in which you originally insert them, use
LinkedHashMap. - If you want the entries kept in a sorted order, use a
NavigableMap, the successor toSortedMap. Java comes with two such implementations:TreeMapandConcurrentHashMap. The latter is thread-safe.
The sorted maps by default use natural order. Optionally, you can provide a Comparator to use for sorting. This has been covered many times already on Stack Overflow, so search to learn more.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | erickson |
| Solution 2 | Basil Bourque |
