Mansukhdeep Thind wrote:Please explain why the output is coming the way it is. What is the logic behind the storage of values in a HashMap?
What exactly do you think is strange about the output? Are you asking why you don't see the elements in the order you put them into the map?
A map does not define any order of its elements, so when you iterate through the map, there is no guarantee that you get the elements in a specific order.
If you need the elements to be displayed in the same order as you put them into the map, then use a LinkedHashMap instead of a HashMap.
Some other points to improve your code:
(1) You are using the raw type HashMap. Use generics to indicate the types of the keys and values in your HashMap. This will make your code mode type-safe.
(2) Program to an interface, not an implementation. Your variable should not be declared as HashMap, but as Map.
(3) You do not need to create new Integer objects explicitly. Let Java do that automatically through autoboxing.
You can iterate through the keys of the map with much simpler code by using the foreach loop syntax. You won't need to explicitly deal with an iterator if you use that:
(Note: Generics, autoboxing and the foreach loop are Java 5 enhancements. If you are using Java 1.4 or older, you can't use those).