CSC 153 Grinnell College Spring, 2005
 
Computer Science Fundamentals
Laboratory Exercise
 

Lists in Java

Goals

This lab applies ideas of box-and-pointer representations and provides practice implementing lists in Java.

Background: Lists in Scheme

The reading for this lab describes box-and-pointer diagrams as a graphical model for lists.

  1. Draw box-and-pointer diagrams for each of the following lists:

    
       ((x) y z)
       (x (y z))
       ((a) b (c ()))
    

Implementing Scheme List Operations in Java

The reading also outlines the implementation of links in Java in two steps.

  1. Class ~walker/java/examples/lists/ListNode.java provides the basic node structure that corresponds to a box and pointer.
  2. Program ~walker/java/examples/lists/ListLikeScheme.java outlines a list class with these methods.

Use these definitions and methods as the base for the following explorations of lists in Java.

  1. Copy ~walker/java/examples/lists/ListNode.java and ~walker/java/examples/lists/ListLikeScheme.java to your account. Compile and run them to check that they work. Also, read through the code. Ask questions about any sections you do not understand.

  2. Add a method second to ListLikeScheme which returns the second element in a list (if present), or which throws a NullPointerException if the list is null or has only one element. (In this and subsequent exercise, you will want to add lines to main to test your methods.)

  3. Add a method count which counts how many times a specified object appears on a list. count should have one parameter -- the object to be counted.

    Note: If item is the object to be counted, you can compare item with any other element with the test item.equals(element). Here you will need to check item with the data in successive nodes.

  4. Add a method last which returns the last item on the list.

  5. Add a method toReverseString which returns a string representing the elements of the list -- ordered from last to first. In writing this code, you should modify the iterative method toString.

  6. Add a method toReverseStringAlt which uses recursion rather than iteration to return the same result as toReverseString.


This document is available on the World Wide Web as

http://www.walker.cs.grinnell.edu/courses/153.sp05/labs/lab-lists-in-java.shtml

created May 4, 2000
last revised March 24, 2005
Valid HTML 4.01! Valid CSS!
For more information, please contact Henry M. Walker at walker@cs.grinnell.edu.