Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hashtable sort by key

 
mickey hendrix
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • 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
 
Paul Clapham
Sheriff
Posts: 21416
33
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • 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.
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • 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:
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic