Rabbit Guy
Rabbit Guy

Reputation: 1892

Hashmap is put into alphabetical order?

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

Answers (4)

Shubham Jain
Shubham Jain

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

Simulant
Simulant

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

nagendra547
nagendra547

Reputation: 6330

LinkedHashMap- preserve the insertion order.
TreeMap - Elements sorted after insertion.

HashMap doesn't maintain any order of inserted elements.

Upvotes: 0

mypetlion
mypetlion

Reputation: 2524

The whole point of a HashMap is that you surrender control of the ordering, so that you can get performance gains on inserting and searching, and other benefits. To take back control of the ordering, look into using a SortedMap.

Upvotes: 0

Related Questions