This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes HashSet order Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "HashSet order" Watch "HashSet order" New topic
Author

HashSet order

Siddharth Raja
Greenhorn

Joined: Nov 11, 2013
Posts: 18


when i run this code it always gives me the output [1, 3, 4, 8]
but i was under the impression that HashSet is unsorted, unordered.
and this happens only for int or Integer values....not String, char, double, etc (i tried)


another thing i discovered


prints output : [1, 3, 4, 8, ds, 5.8]

why so?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18754
    
  40

Siddharth Raja wrote:

when i run this code it always gives me the output [1, 3, 4, 8]
but i was under the impression that HashSet is unsorted, unordered.
and this happens only for int or Integer values....not String, char, double, etc (i tried)


Just because the example that you provided looks sorted, doesn't mean that it is sorted. Just because the result is always in the same order doesn't mean that it is ordered either. The hashset has an algorithm to hold the items -- the ordering and sort order (if any) is purely an implementation detail and may differ with different JVMs, versions of Java, under different conditions, etc.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: HashSet order