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.

2
  • 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. Commented Jun 10, 2013 at 6:15
  • This sounds like an 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. Commented Jun 10, 2013 at 7:22

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.