Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Senior Coder
    Join Date
    Dec 2005
    Location
    Slovenia
    Posts
    2,017
    Thanks
    120
    Thanked 77 Times in 77 Posts

    hashSet order of elements

    Code:
          HashSet hs1 = new HashSet();
          hs1.add("plantae");
          hs1.add("2");
          hs1.add("animalia");
          while  (it1.hasNext())
          {
           System.out.println(it1.next());
          }
    -->
    Code:
    2
    animalia
    plantae
    How to make this work from 'plantae ?
    Last edited by BubikolRamios; 02-05-2010 at 08:13 PM.

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    28,252
    Thanks
    82
    Thanked 4,747 Times in 4,709 Posts
    Don't use a HashSet. By definition, *any* kind of hash table WILL NOT store it's contents in alphabetical order.

    If you want an ordered collection, use an ordered collection type. Period.

    It's actually somewhat coincidental that you got the values in the order that you did. If you had tried a larger list of values, I'm sure they wouldn't have been that ordered.

    Now...if you want "a" to come before "1", then you will have to also generate a custom comparator. But that still shouldn't work with HashSet.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •