The JavaTM Tutorial
Previous Page Lesson Contents Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Collections
Lesson: Interfaces

Answers to Questions and Exercises:

Questions

  1. Question: Which two of the following interfaces are at the top of the hierarchies in the Java Collections Framework?
    • Set
    • Map
    • Queue
    • SortedMap
    • Collection
    • List

    Answer: Map and Collection are at the top of the hierarchies in the Java Collections Framework. Set, Queue, and List are subinterfaces of Collection. SortedMap is a subinterface of Map.

  2. Question: Which of the following interfaces does not allow duplicate objects?
    • Queue
    • Set
    • List

    Answer: Set does not allow duplicate objects.

  3. Question: In order for objects in a List to be sorted, those objects must implement which interface and method?

    Answer: The objects must implement the Comparable interface and its compareTo method.

  4. Question: True or false: The element method alters the contents of a Queue.

    Answer: False. The element method retrieves, but does not remove, the head of the queue.

Exercises

  1. Exercise: Write a method with the signature:
    public Collection<String> filter(Collection<String> c)
    
    that (1) traverses through the elements in c using an Iterator, (2) checks whether each element meets a certain condition (in a separate method condition which you do not need to define right now), and (3) if the object meets the condition, adds it to the new Collection to return. The method should not modify the Collection c. Design the method to work on any collection of Strings. Only the condition method should have application-specific code; we will define this method as part of an application in the exercises for the Implementations lesson.

    Answer:

    public Collection<String> filter(Collection<String> c) {
        Collection<String> filteredCollection = new ArrayList<String>();
        for (Iterator<String> i = c.iterator(); i.hasNext(); ) {
            String s = (String) i.next();
            if (condition(s)) {
                filteredCollection.add(s);
            }
        }
        return filteredCollection;
    }
    
  2. Exercise: Write a method with the signature:
    public List<Integer> reverse(List<Integer> orginalList)
    
    that returns a new List that contains the same Integer objects as the originalList argument, but in reverse order. The method should not modify the orginalList object.

    Answer:

    public List<Integer> reverse(List<Integer> orginalList) {
        List reversed = new LinkedList<Integer>();
        for (int i = orginalList.size() - 1; i >= 0; i--) {
            reversed.add(orginalList.get(i));
        }
        return reversed;
    }
    

Previous Page Lesson Contents Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.