//HashSetTest.java //generate random ints, add to an hashset, display them. //HashSet is one of the built-in classes of the Java Collections Framework. //implements a mathematical set: // unique (no duplicates) objects // no index // no order //A set is like a bag with the objects in it. There is no notion of sequence, // index, or order; the objects are jumbled together in the bag. // Methods: // add(object) won't add if a copy of the object is already in the set // remove(object) // clear() // contains(object) // size() // isEmpty() // iterator() itertion will be in unpredictable order //Collections sort, reverse, shuffle can NOT be used. //the objects in the bag are not in any order so they can't be sorted, //reversed, or shuffled. //HashSet is implemented with hashing which makes add, remove, and contains //very efficient (i.e. very fast), O(1) on average. //User classes MUST override equals() and hashcode() to be used in a HashSet. //see the DatesHashSetTest.java // http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashSet.html //***run this with 10 ints in range 5 to see the duplicates rejected and the //unpredictable iteration order import java.util.*; import javax.swing.*; public class HashSetTest { public static void main(String[] args) { String input; int size; int range; int randInt; HashSet myHashSet = new HashSet(); //*** 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 (myHashSet.add(new Integer(randInt))) System.out.println(" Added to set!"); else System.out.println(" Duplicate already in set. Not added to set!"); } Iterator it = myHashSet.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 set: " + Collections.min(myHashSet)); System.out.println("Max value in hash set: " + Collections.max(myHashSet)); } }