Laboratory: Implementing Collections
CSC 207 Algorithms and Object Oriented Design Spring 2010

Summary: In this lab, you will experiment with implementations of methods for collections.

Preparation

In an earlier lab, you should have already downloaded the code from the book and configured Ant/JDE to use it. If you have not already done so, do it now.

Exercises

Exercise 1

The Java Collections API defines the following methods in the Collection interface.

  /** Adds all of the elements in the specified collection to this 
   *  collection. */
  public boolean addAll(Collection<? extends AnyType> c);

  /** Removes all this collection's elements that are also contained
   *  in the specified collection. */
  public boolean removeAll(Collection<?> c);

  /** Returns true if this collection contains all of the elements in
   *  the specified collection.  */
  public boolean containsAll(Collection<?> c);
  1. Add the above methods to the Collection interface in package weiss.util.
  2. Implement the above methods in AbstractCollection in the same package.
  3. Recompile the book code using Build from the JDE menu.
  4. Test the implementation of your methods by writing a small driver program that creates two instances of collections from the book code (e.g., use weiss.util.LinkedList and its add method) and uses one of the above methods on them.

    Note: Remember that your program will have to know where to find the weiss packages. In an earlier lab, you modified your .emacs file so that JDE knew this. If you try to compile your driver program from the command line, you will have to manually specify it with the -classpath argument to javac.

Exercise 2

Two Collection objects are considered equal under one of two conditions. Either or
  1. Why is it impossible for a Collection to implement both the Set and the List interface?
  2. Add an implementation of equals to AbstractCollection that adheres to the specification above.
  3. Test your implementation by writing a small driver program.

For those with extra time

According to the Java API, the general contract of the hashCode method is:
-- Object (Java 2 Platform SE 5.0), hashCode
Add an implementation of hashCode to the weiss.util.AbstractCollection class that satisfies this contract. (Hint: sum the hash codes of the objects in the collection.)
Jerod Weinman
Created: 12 January 2009
Adapted from Mark Allen Weiss, Data Structures and Problem Solving Using Java Exercises 15.11 and 15.13.