//DatesTreeSetTest.java //demo of user class in a tree set. //create random Dates and add to TreeSet. //How are duplicates determined? user class Date must override equals() and hashCode() //TreeSet of user class needs to indicate what Comparator to use for the ordering. import java.util.*; import javax.swing.*; public class DatesTreeSetTest { public static void main(String[] args) { String input; int size; TreeSet myDatesTreeSet = new TreeSet(new DateComparator()); 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 (myDatesTreeSet.add(randDate)) System.out.println(" Added to set!"); else System.out.println(" Duplicate already in set. Not added to set!"); } Iterator it = myDatesTreeSet.iterator(); System.out.println("Here are your unique random dates in the set: "); while (it.hasNext()) System.out.print(it.next() + " "); System.out.println(); //min and max using Comparator System.out.println("Min value in hash set: " + Collections.min(myDatesTreeSet, new DateComparator())); System.out.println("Max value in hash set: " + Collections.max(myDatesTreeSet, new DateComparator())); 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; //month = (int)(Math.random()*12+1); month = 1; //for testing/demo use Jan 2006 to see dups 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); } }