Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting a HashTable

 
Frank E Robinson
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello All,
Would you give me some insight on how to sort values in a has table. I just started teaching myself Java. Below is my code that creates a has with some values. If you could point me to some good references that would be great also.
thanks in advance
import java.util.*;
public class hs
{
static HashSet myHS = new HashSet();

public static void main(String[] arg)
{

createHS();
showHS();
}
public static void createHS()
{
String s1="B", s2="E", s3="U", s4="A", s5="Z", s6="T";
myHS.add(s1);
myHS.add(s2);
myHS.add(s3);
myHS.add(s4);
myHS.add(s5);
myHS.add(s6);
}

public static void showHS()
{
Iterator i = myHS.iterator();
while( i.hasNext() )
{
System.out.println(" tool: " + i.next() );
}
}
}
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You really can't sort the entries in a Hashtable, HashMap or HashSet. They're not stored in sorted order when you put them into the map, and you can't reorder them later. If you want to sort something, and you want to simultaneously maintain a Map relationship between keys and values, then you want to use a SortedMap - an interface which has one standard implementation, TreeMap. That's the class you want.
 
Frank E Robinson
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jim, I'll look into SortedMap.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic