Sample Quiz Answers
For Chapter 12

THIS PAGE CONTAINS SAMPLE ANSWERS to the Quiz on Chapter 12 of this on-line Java textbook. Note that in many cases, there are lots of correct answers to a given question.

Question 1: What is meant by generic programming and what is the alternative?

Answer: Generic programming means writing data structures and subroutines that can be used for many different types of data. The alternative would be to write a new data structure or subroutine for each different type of data, even when they would all be essentially identical except for the type name. For example, a single generic sort routine could be used for sorting arrays that contain data of any type. The alternative is one routine for sorting arrays of integers, one for sorting arrays of strings, one for storing arrays of real numbers, and so on.

Question 2: Java does not support generic programming with the primitive types. Why not? What is it about generic programming in Java that prevents it from working with primitive types such as int and double.

Answer: In Java, generic programming means working with values of type Object. Since every class is a subclass of Object, a data structure that holds Objects can hold objects belonging to any class, and a subroutine that has a parameter of type Object can be applied to an object belonging to any class. Such data structures and subroutines are generic -- but only for objects. However, in Java, values belonging to the primitive types are not objects. So, you can't use ints or doubles in places where objects are required. This means you can't use them with generic data structures and subroutines.

Question 3: What is an iterator and why are iterators necessary for generic programming?

Answer: One of the principle features of Java's generic programming framework is Collections. There are several types of collection (including LinkedLists, ArrayList, TreeSet, and HashSet). In order to deal with all the different types of collection in a generic way, we need a generic way to access all the elements in a collection. An iterator makes this possible. An iterator is an object associated with a collection that makes it possible to traverse the collection (that is, to visit each of the items in the collection in turn). Code written using iterators will work for any type of Collection.

Question 4: Suppose that integers is a variable of type Collection and that every object in the collection belongs to the wrapper class Integer. Write a code segment that will compute the sum of all the integer values in the collection.

Answer: We need to use an Iterator to access all the items in the Collection. To get the integer value from an object of type Integer, we can call its intValue() method.

         int sum = 0;  // This will be the sum of all the integers.

         Iterator iter = integers.getIterator();
         while ( iter.hasNext() ) {
            Object item =;   // Next item as an Object.
            Integer num = (Integer)item; // Type-cast item to an Integer.
            sum = sum + num.intValue();  // Add the number to the sum

Question 5: Interfaces such as List, Set, and Map define abstract data types. Explain what this means.

Answer: An abstract data type is defined by the operations that can be performed on it, not by the way the data is actually stored or by the way the operations are implemented. An interface such as List defines operations that can be performed, but says nothing about how they are to be implemented. In fact, there can be many different implementations. For example, both LinkedList and ArrayList implement the List interface. They are different "concrete" data types that represent the same abstract data type.

Question 6: What is the fundamental property that distinguishes Sets from other types of Collections?

Answer: A Set cannot contain repeated elements. (The equals() method is used to test whether two objects should be considered the same.)

Question 7: What is the essential difference in functionality between a TreeMap and a HashMap?

Answer: The key/value pairs in a TreeMap are sorted so that the keys are in ascending order. (For this reason, it must be possible to compare the keys in a TreeMap, either by using the compareTo() method or a Comparator.)

Question 8: Explain what is meant by a hash code.

Answer: The hash code of an object is an integer that tells where that object should be stored in a hash table. A hash table is an array of linked lists. When an object is stored in a hash table, it is added to one of these linked lists. The object's hash code is the index of the position in the array where the object is stored. All objects with the same hash code go into the same linked list.

Question 9: Modify the following Date class so that it implements the Comparable interface. The ordering on objects of type Date should be the natural, chronological ordering.

      class Date {
         int month;  // Month number in range 1 to 12.
         int day;    // Day number in range 1 to 31.
         int year;   // Year number.
         Date(int m, int d, int y) { // Convenience constructor.
            month = m;
            day = d;
            year = y;

Answer: A compareTo() method must be added to the class, and the class must be declared to implement the Comparable interface. To compare two dates, first try comparing the years. If the years are equal, try comparing the months. If the months are also equal, compare the days.

      class Date implements Comparable {
         int month;  // Month number in range 1 to 12.
         int day;    // Day number in range 1 to 31.
         int year;   // Year number.
         Date(int m, int d, int y) { // Convenience constructor.
            month = m;
            day = d;
            year = y;
         public int compareTo( Object obj ) {
                // The parameter must be of type Date.  Otherwise,
                // a ClassCastException will be thrown.  The return
                // value is negative if this Date comes before otherDate,
                // it's zero if the two dates are the same, and
                // it's positive if this Date comes after otherDate.
            Date otherDate = (Date)obj;  // Try to type-cast the object
                                         // into a Date.
            if (year < otherDate.year)
               return -1;
            else if (year > otherDate.year)
               return 1;
            else { // Years are equal; compare months.
               if (month < otherDate.month)
                  return -1;
               else if (month > otherDate.month)
                  return 1;
               else { // Years and months are equal; compare days.
                  if (day <
                     return -1;
                  else if (day >
                     return 1;
                     return 0;

Question 10: Suppose that syllabus is a variable of type TreeMap, the keys in the map are objects belonging to the Date class from the previous problem, and the values are of type String. Write a code segment that will write out the value string for every key that is in the month of September, 2002.

Answer: I will give two solutions. One of them simply looks up each date in September, 2002 in the map and prints the corresponding value, if there is one. The other iterates though a submap that contains all the entries for dates in that month.

A solution using the map's get() method:

      for (int day = 1; day <=30; day++) {
           // Get the info for one day in September, 2002;
         Date date = new Date(9,day,2002); // The key.
         Object info = syllabus.get(date); // Get the value for that key.
                                           // (Can be null.)
         if (info != null)
            System.out.println("September " + day + ": " + info);

A solution using a submap (harder, but more efficient):

      Date startDate = new Date(9,1,2002);  // Starting date for submap.
      Date endDate = new Date(10,1,2002);   // Ending date for submap.
                                            // (Remember that the end date
                                            // is not included.)
      Map september = syllabus.subMap(startDate, endDate);
      Iterator iter = september.entrySet().iterator();
      while (iter.hasNext()) {
         Map.Entry entry = (Map.Entry);
         Date date = (Date)entry.getKey(); // Get the date so I can print it.
         String info = (String)entry.getValue();  // The value for that date.
         System.out.println("September " + ": " + info);

[ Chapter Index | Main Index ]