HOMEWORK 10 - SAMPLE ANSWERS 1. (a) Since the compareTo method uses compareTo from the String class, dates are ordered based on month first, then day, and then finally year. (b) public class DateComparator implements Comparator { public int compare(Date d1, Date d2) { String year1 = d1.dateString.substring(6); String year2 = d2.dateString.substring(6); String month1 = d1.dateString.substring(0,3); String month2 = d2.dateString.substring(0,3); String day1 = d1.dateString.substring(3,6); String day2 = d2.dateString.substring(3,6); String date1 = year1 + "/" + month1 + "/" + day1; String date2 = year2 + "/" + month2 + "/" + day2; return date1.compareTo(date2); } } (c) DateComparator dc = new DateComparator(); if (dc.compare(d1,d2) < 0) System.out.println(d1); else System.out.println(d2); (d) Collections.sort(dateList, new DateComparator()); 2. (a) Set showSet = showMap.keySet(); for (String tvShow: showSet) if (showMap.get(tvShow).equals("ABC")) System.out.println(tvShow); (b) Set showSet = networkMap.get("FOX"); ArrayList showList = new ArrayList(showSet); Arrays.sort(showList); System.out.println(showList); 3. public static int countUnique(ArrayList list) { Set set = new HashSet(); for (E element : list) set.add(element); return set.size(); } 4. (a) 0: 06/13/1999 1: 2: 01/01/2008 3: 02/10/1994 4: 03/31/1868 5: 04/18/2012 6: 09/24/1776 7: 8: 9: 01/18/1987 (b) 0: 1: 2: 01/01/2008, 02/10/1994, 04/18/2012 3: 09/24/1776 4: 03/31/1868 5: 6: 7: 8: 9: 01/18/1987, 06/13/1999 5. (a) When an element is hashed into the table, the hash function chooses a random position for the element. However, when we search for the element, using the same hash function will not likely produce the same location since the function is based on a random number generator. The hash function should yield the same value when the element is inserted and when we search for it. (b) In this case, the sum of the digits may exceed 49 in which case we'd get a table position that is invalid.