File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HashSet order

 
Siddharth Raja
Greenhorn
Posts: 18
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Marshal
Pie
Posts: 20828
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic