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 can't understand the output Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "can Watch "can New topic

can't understand the output

sharma sachin

Joined: Nov 13, 2009
Posts: 24

the output of the above program is:
contents of HashSet are:[1,3,4,5,97,7,56,72]
can any one please explain this output to me.......
i knows that if i will use TreeSet instead of HashSet then the output will be in sorted order becoz TreeSet is Sorted collection
but in case of HashSet how this output comes after successive execution.....
Andrey Kozhanov
Ranch Hand

Joined: Mar 12, 2010
Posts: 79
It is set in HashSet documentation:

This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46383
A set does not imply an order of its elements. The set {1, 2, 3} and the set {3, 2, 1} are mathematically identical. You cannot therefore expect any order from a set. A TreeSet is different, because it implements sorting in addition to the usual Set operations. A LinkedHashSet is also different, but I shall let you look it up for yourself.
subject: can't understand the output
It's not a secret anymore!