aspose file tools*
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
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: 18120
    
  39

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
 
Similar Threads
Question About TreeSet?
K&B - Erratum ?
java pass by value.
Doubt in function remove in Set
Confusion on HashSet