• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Query- Set (ordering of strings)

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear Java Community

I kindly want to inquire, why is a set of strings printed out in alphabetical order but not the first element. Using the following code as an example:



The result printed is (from Eclipse IDE):
[red, green, yellow]

Questions:
------------

1) Why is the element 'red' first (it is alphabetically found lower than 'green')?
2) Why are the elements sorted in this set (is it sorted alphabetically or using the sum of ASCII codes)?

Any help is much appreciated.
 
Rancher
Posts: 4801
50
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
They're not sorted.
As the JavaDoc says for HashSet:
"
It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.
"
 
Saloon Keeper
Posts: 14263
321
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Note that with such a small data set, you can always find some kind of pattern.

I might as well ask "why are the elements sorted alphabetically by their last letter?"
 
Lasagna is spaghetti flvored cake. Just like this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic