wood burning stoves 2.0*
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 OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA 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: 18765
    
  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