File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Clarification regarding HashMap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Clarification regarding HashMap" Watch "Clarification regarding HashMap" New topic

Clarification regarding HashMap

Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157


Please go through the code below;

This gives the output as :

retrieving keys from hashmap
hashMap values -----[3, 1, 2]

Please explain why the output is coming the way it is. What is the logic behind the storage of values in a HashMap?

Mansukhdeep Thind

~ Mansukh
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15092

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.

Like this:

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).

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: Clarification regarding HashMap
It's not a secret anymore!