Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Clarification regarding HashMap

 
Mansukhdeep Thind
Ranch Hand
Posts: 1158
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Please go through the code below;


This gives the output as :

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

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

Regards
Mansukhdeep Thind
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15369
40
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic