aspose file tools*
The moose likes Java in General and the fly likes Why the same sequence from HashMap, HashTable, HashSet in Java Collections? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Why the same sequence from HashMap, HashTable, HashSet in Java Collections?" Watch "Why the same sequence from HashMap, HashTable, HashSet in Java Collections?" New topic
Author

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

Hilary Mann
Greenhorn

Joined: Jun 07, 2012
Posts: 13
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

Joined: Jan 28, 2008
Posts: 5575

Look at java.util.HashMap#hash and java.util.HashMap#indexFor
dennis deems
Ranch Hand

Joined: Mar 12, 2011
Posts: 808
Perhaps equally relevant (perhaps more so) is java.util.AbstractMap.toString
Stuart A. Burkett
Ranch Hand

Joined: May 30, 2012
Posts: 679
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

Joined: Aug 16, 2005
Posts: 14423
    
  23

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


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why the same sequence from HashMap, HashTable, HashSet in Java Collections?