// File: SetTest.java // Shows basic set operations add, remove, and contains. // A HashSet is created and the user can add and remove Strings. // Note that attempts to add Strings already in the set are ignored, // as are attempts to remove a String that is not in the set. // The print() method uses an Iterator and Iterator methods hasNext() and // next() to retrieve each object in the set. import java.util.HashSet ; import java.util.Iterator ; import java.util.Set ; import javax.swing.JOptionPane ; public class SetTest { public static void main(String[] args) { Set names = new HashSet() ; // add a bunch of names String input = JOptionPane.showInputDialog ("Add a name (or Cancel when done)") ; while ( input != null ) { System.out.println("Adding " + input + "...") ; names.add( input ) ; print(names) ; input = JOptionPane.showInputDialog ("Add a name (or Cancel when done)") ; } // remove some names input = JOptionPane.showInputDialog ("Name to remove? (Cancel when done)") ; while ( input != null ) { System.out.println("Removing " + input + "...") ; names.remove( input ) ; print(names) ; input = JOptionPane.showInputDialog ("Name to remove? (Cancel when done)") ; } // do some searches String target = JOptionPane.showInputDialog ("Name to find? (Cancel when done)") ; while ( target != null ) { if ( names.contains(target) ) { System.out.println( target + " is in the set" ) ; } else { System.out.println( target + " is NOT in the set" ) ; } target = JOptionPane.showInputDialog ("Name to find? (Cancel when done)") ; } } /** Prints the contents of a set @param s a set */ private static void print(Set s) { Iterator iter = s.iterator() ; System.out.print("{ ") ; while (iter.hasNext()) { System.out.print(iter.next() + " ") ; } System.out.println("}\n") ; } } /* Sample output: Adding Moe... { Moe } Adding Larry... { Moe Larry } Adding Curly... { Moe Larry Curly } Adding Shemp... { Moe Shemp Larry Curly } Removing Moe... { Shemp Larry Curly } Removing Larry... { Shemp Curly } Removing Bob... { Shemp Curly } Shemp is in the set Curly is in the set Moe is NOT in the set */