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

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


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.


Exercise 1

The Java Collections Framework 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.

    Do not put your test class in the book code folder. Instead, put it wherever you regularly place code for this course's labs.

    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 the following 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 Platform SE 6), 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.)
Created: Jerod Weinman, 12 January 2009
Modified: Jerod Weinman, 18 January 2011
Modified: Jerod Weinman, 6 April 2011

Adapted from Mark Allen Weiss, Data Structures and Problem Solving Using Java(3/e) Exercises 15.11 and 15.13.

Copyright © 2009-2011 Jerod Weinman.
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License .