• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Hashtable sort by key

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hello to everybody
I have a problem sorting an Hashtable by the key:this is a String like an ip like "120.3.5.3" and the object is generic...anything:
Example:

Hashtable hash = new Hashtable;
hash.put("12.5.8.10",myObject);
hash.put("12.7.8.10",myObject);
hash.put("12.5.9.10",myObject);
hash.put("12.24.8.10",myObject);
hash.put("12.5.8.11",myObject);

Now that I have valorized the items I need to order the hashtable in ascending mode by the key....
How can I do?Ot I have to use another Struct ( like Set or Map ) in witch put the data?
thanks for help
 
Marshal
Posts: 28226
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
TreeMap is a sorted Map. From its API documentation:

"This class guarantees that the map will be in ascending key order, sorted according to the natural order for the key's class (see Comparable)"

The keys need to implement Comparable, so since your keys are Strings, they do that. No problem there.
 
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, you could have used TreeMap from the get-go. Or you could copy your
hashtable into a TreeMap if other code is providing the hash table

And if you are stuck with a hash table, but all you need to do is iterate
through it, copy the keys into an array and sort it:
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic