Sun Java Solaris Communities My SDN Account Join SDN
 
Tutorials & Code Camps

Java Technology Fundamentals - July's Program Challenge

 

New-to-Java Programming Center
Technology Fundamentals

For July's Challenge Program PhoneList, you created a program that maintains a phone list of your friends: Show the differences when traversing the entries based upon insertion order, hash code order, and sorted order by printing out the hash table keys and values.

A possible solution to the July 2002 Java Technology Fundamentals Program Challenge, PhoneList:

import java.util.*;

public class PhoneList {
   public static void main(String args[]) {
     // Create map - maintain insertion order
     Map map = new LinkedHashMap();

     // Add members
     map.put("George", "202-456-1111");
     map.put("Bill", "212-348-8882");
     map.put("Hillary", "202-224-4451");
     map.put("Elvis", "901-332-3322");
     map.put("Jimmy", "229-924-6935");

     // Print map
     print(map, "Insertion Order:");

     // Convert map to regular
     map = new HashMap(map);

     // Print map
     print(map, "Hashing Order:");

     // Convert map to sorted
     map = new TreeMap(map);

     // Print map
     print(map, "Sorted");
   }

   private static void print(Map map, String message) {
     System.out.println(message);
     Set entries = map.entrySet();
     Iterator iterator = entries.iterator();
     while (iterator.hasNext()) {
       Map.Entry entry = (Map.Entry)iterator.next();
       System.out.println(entry.getKey() + " : "
         + entry.getValue());
     }
     System.out.println();
   }
}

Your result should look something like the following:

Insertion Order:
George : 202-456-1111
Bill : 212-348-8882
Hillary : 202-224-4451
Elvis : 901-332-3322
Jimmy : 229-924-6935

Hashing Order:
Hillary : 202-224-4451
George : 202-456-1111
Bill : 212-348-8882
Jimmy : 229-924-6935
Elvis : 901-332-3322

Sorted
Bill : 212-348-8882
Elvis : 901-332-3322
George : 202-456-1111
Hillary : 202-224-4451
Jimmy : 229-924-6935

Have a question about programming? Use Java Online Support.