0

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.

Raja
  • 239
  • 1
  • 5
  • 18
  • Can you please tell why you need to use two different structures? If data in both the structures are related then I would recommend to use One structure or POJO and add it to List , say, so that your data is not scattered for given use case. Behavior of these is already explained by Luiggi. – Harish Kumar Jun 10 '13 at 06:15
  • This sounds like an [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Why do you care about the order of elements in the `Map` (especially if you already have a `List` to keep the order). The `Map` should usually be accessed via the key, in that case the order does not matter. – Joachim Sauer Jun 10 '13 at 07:22

1 Answers1

3

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"?

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332