Raja
Raja

Reputation: 249

Hashmap and arraylist adding values differently in java

I want to add values in arraylist and as well as in hashmap.While i adding values i noted that map adding values in front and list adding values at last.But i want both to be added in one way.How to do that.

My values to be added in hashmap are 4055,5040 And in my list 20,37

But while adding list gives the expected result but map giving me the output as 5040,4055.

Upvotes: 0

Views: 148

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

Use LinkedHashMap instead of HashMap. The former preserves the order of the insertion of the elements.

From its JavaDoc (emphasis mine):

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

This will make your Map and your List (backed by an ArrayList) have the elements in the same order.

Not sure how have you designed your app, but I recommend you to program oriented to interfaces (Map, List, etc...) instead of classes (HashMap, ArrayList, etc...). More info: What does it mean to "program to an interface"?

Upvotes: 3

Related Questions