//DatesHashsetTest.java //demo of user class in a hash set. //create random Dates and add to HashSet. //How are duplicates determined? user class Date must override equals() and hashCode() import java.util.*; import javax.swing.*; public class DatesHashSetTest { public static void main(String[] args) { String input; int size; HashSet myDatesHashSet = new HashSet(); input = JOptionPane.showInputDialog( "Enter number of random dates" ); size = Integer.parseInt( input ); Date randDate; for (int i=1; i<=size; i++) { randDate = generateRandomDate(); System.out.print(randDate); if (myDatesHashSet.add(randDate)) System.out.println(" Added to set!"); else System.out.println(" Duplicate already in set. Not added to set!"); } Iterator it = myDatesHashSet.iterator(); System.out.println("Here are your unique random dates in the set: "); while (it.hasNext()) System.out.print(it.next() + " "); System.out.println(); System.exit(0); } //generate a random Date public static Date generateRandomDate() { int year, month, day=0; //year = (int)(Math.random()*20+1995); // +/- 10 years from 2005 year = 2006; //365 possible random dates... month = (int)(Math.random()*12+1); switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: day = (int)(Math.random()*31+1); break; case 4: case 6: case 9: case 11: day = (int)(Math.random()*30+1); break; case 2: if (year%4==0 && year%100!=0 || year%400==0) //leap year test day = (int)(Math.random()*29+1); else day = (int)(Math.random()*28+1); break; } return new Date(month,day,year); } }