Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why the same sequence from HashMap, HashTable, HashSet in Java Collections?

 
Hilary Mann
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For different number of items, we always get the same sequence of output which is neither random nor based on any algorithm...:

How does it work, then?
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look at java.util.HashMap#hash and java.util.HashMap#indexFor
 
dennis deems
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Perhaps equally relevant (perhaps more so) is java.util.AbstractMap.toString
 
Stuart A. Burkett
Ranch Hand
Posts: 679
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hilary Mann wrote:nor based on any algorithm...:

It probably is based on some algorithm, but the specification doesn't mandate any particular order for a Hash based collection, so it is up to the implementation what order items are returned in. If you run your program on a different version of the JRE or a JRE from a different manufacturer you may (or may not) get a different order and it may (or may not) be consistent in the ordering.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15281
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HashMap, Hashtable and HashSet are not ordered collections.

In other words: they don't contain items in any particular order, like a List would. You can see for example a HashSet as a bag that contains items. The items are just jumbled up inside the bag, not in any particular order - if you put your hand in and take an item from the bag, you don't know which one you're going to take.

Don't write a program that relies on the items being picked out of the Set in any particular order, because the order is undefined. If the order is important, use another collection class (an ArrayList or LinkedList, for example, or a LinkedHashSet).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic