This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Sorting a HashTable Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Sorting a HashTable" Watch "Sorting a HashTable" New topic
Author

Sorting a HashTable

Frank E Robinson
Greenhorn

Joined: Nov 22, 2003
Posts: 2
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

Joined: Jan 30, 2000
Posts: 18670
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.


"I'm not back." - Bill Harding, Twister
Frank E Robinson
Greenhorn

Joined: Nov 22, 2003
Posts: 2
Thanks Jim, I'll look into SortedMap.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Sorting a HashTable
 
Similar Threads
Problem with String
nested class Danchisholm ques.
nested class Danchisholm ques.
Strings
Strings, StringBuffer and equals()