Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HashSet order

 
Siddharth Raja
Greenhorn
Posts: 18
  • 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: 20894
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 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

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic