//TreeSetTest.java //generate random ints, add to an treeset, display them. //basically, same as HashSetTest.java //TreeSet is one of the built-in classes of the Java Collections Framework. //implements a mathematical set: // unique (no duplicates) objects // no index // *** ordered (unlike HashSet) // Methods: // add(object) // remove(object) // clear() // contains(object) // size() // isEmpty() // iterator() ** itertion will be in sorted order //Collections sort, reverse, shuffle can NOT be used. //***Implemented by a binary search tree which makes add, remove, contains all efficient, //i.e. O(lg n), but not as efficient as hashing. //***Hashing: very efficient but not sorted. //***Binary tree: not as efficient but sorted. // http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeSet.html //run this with 10 ints in range 5 to see the duplicates rejected and the //***sorted iteration order import java.util.*; import javax.swing.*; public class TreeSetTest { public static void main(String[] args) { String input; int size; int range; int randInt; TreeSet myTreeSet = new TreeSet(); //*** 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); //*** add returns true if added, false if duplicate and not added if (myTreeSet.add(new Integer(randInt))) System.out.println(" Added to set!"); else System.out.println(" Duplicate already in set. Not added to set!"); } Iterator it = myTreeSet.iterator(); System.out.println("Here are your unique random integers in the set: "); while (it.hasNext()) System.out.print(it.next() + " "); System.out.println(); System.out.println("Min value in hash tree: " + Collections.min(myTreeSet)); System.out.println("Max value in hash tree: " + Collections.max(myTreeSet)); } }