Reputation: 1892
I have a HashMap defined as follow:
private final Map<String, DataTable> reports = new HashMap();
When I put new entries into this HashMap they end up in Alphabetical order based on the key. Why is it doing this? How do I put them in the order I added them to the HashMap?
Upvotes: 3
Views: 3424
Reputation: 33
HashMap doesn't add the values in the way you are adding it just adds the value randomly based on keys. For adding the values in the order you are adding use LinkedHashMap
or if you want the Map in Alphabetically sorted order then use TreeMap. I hope this clears your doubt.
Upvotes: 0
Reputation: 20142
A HashMap
does explicitly define NO order of the elements you add. Like in a HashSet
the elements are ordery by their hashcode and this is more or less random.
If you want to preserve the order in the Map in the order of insertion you can use a LinkedHashMap instead. Or use a TreeMap if the elements should be sorted after the insertion.
Upvotes: 4
Reputation: 6330
LinkedHashMap- preserve the insertion order.
TreeMap - Elements sorted after insertion.
HashMap doesn't maintain any order of inserted elements.
Upvotes: 0