//TreeMapTest.java //generate random int and string pair, add to an treemap, display them. //TreeMap is one of the built-in classes of the Java Collections Framework. //implements a sorted key/value pair mapping: // unique (no duplicates) keys // no index // no order // Methods: // put( key object, value object) won't add if a copy of the object is already in the set // remove( key object) // clear() // containsKey( key object) // size() // isEmpty() // http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html import java.util.*; import javax.swing.*; public class TreeMapTest { public static void main(String[] args) { String input; int size; int range; int randInt; Integer newKey; TreeMap myTreeMap = new TreeMap(); //*** input = JOptionPane.showInputDialog( "Enter number of random ints to generate" ); size = Integer.parseInt( input ); input = JOptionPane.showInputDialog( "Enter upper range of the random ints" ); range = Integer.parseInt( input ); for (int i=1; i<=size; i++) { randInt = (int)(Math.random()*range); System.out.print("generated int: " + randInt); //*** put returns previous value if added, so check if already exists first newKey = new Integer(randInt); if (!myTreeMap.containsKey(newKey)) { myTreeMap.put(newKey, "random string value "+Math.random()); System.out.println(" Added to map!"); } else System.out.println(" Duplicate already in map. Not added to map!"); } //can not iterate over a TreeMap, must get Set of Map.Entry Iterator it = myTreeMap.entrySet().iterator(); System.out.println("Here are the pairs in the map: "); while (it.hasNext()) System.out.println(it.next()); System.out.println(); } }