• 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 (add method)

 
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, questions about the following code:



The result is (from Eclipse IDE):

[red, green, [red, blue, yellow], yellow]

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

1) Why is set2 added in index 2 (is it because 'red' is alphabetically higher than set1 'yellow' )?
2) Why does set 1 order it`s elements as [red, green, yellow], does it have a alphabetical natural ordering?

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
HashSets do not guarantee any ordering.
 
Saloon Keeper
Posts: 14260
321
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
To further generalize, NO set that doesn't implement SortedSet guarantees any particular sorting order.
 
Marshal
Posts: 76394
364
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Any ordering would have to do with the rightmost nybble of the hash code after re‑hashing. What is more, if you keep adding elements, when you get beyond about twelve elements, you will suffer a rehashing of every element as the backing array is enlarged, and you may get a different order, now using more bits of the hash code.
So, to add to what Stephan said, hash‑based collections more or less guarantee unpredictable iteration orders.
 
If you have a bad day in October, have a slice of banana cream pie. And this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic