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

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: 28295
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:
 
Today's lesson is that you can't wear a jetpack AND a cape. I should have read this tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic