©2006 Felleisen, Proulx, et. al.

10  Using ArrayLists, Traversals, Loops and Function Objects


In this lab you will first learn how to use and mutate ArrayList objects. We will use the generics (type parameters), but will do so by example, rather than through explanation of the specific details.

In the second part of the lab you will learn how to use Java while statement and Java for statements to implement imperative loops.

Throughout the lab we will work on lists of music albums.

10.1  Class for Albums

Launch Eclipse, start a Project called Lab10 and import the files from lab10.zip. Take a look at the Album class. You 'll notice that the fields are private and we provide getter methods for the user who wants to access a field outside the class. This way, the user can retrieve the value of a field without changing it.

Task 1:

Design the class BeforeYear that implements the ISelect interface with a method that determines whether the given album was recorded before some fixed year. Remeber to test the method.

10.2  Using ArrayList with Mutation

Open the web site that shows the documentation for Java libraries http://java.sun.com/j2se/1.5.0/docs/api/.

Find the documentation for ArrayList.

Here are some of the methods defined in the class ArrayList:

// how many items are in the collection
int size();

// add the given object of the type E at the end of this collection
// false if no space is available
boolean add(E obj);

// return the object of the type E at the given index
E get(int index);

// replace the object of the type E at the given index 
// with the given element
// produce the element that was at the given index before this change
E set(int index, E obj);

Other methods of this class are isEmpty (checks whether we have added any elements to the arraylist), contains (checks if a given element exists in the ArrayList -- using the equals method), set (mutate the element of the list at a specific position), size (returns the number of elements added so far). Notice that, in order to use an ArrayList, we have to add

import java.util.ArrayList;

at the beginning of our class file.

The methods you design here should be added to the Examples class, together with all the necessary tests.

Task 2:

10.3  Converting recursive loops into iterative while loops

We will look together at the first two examples of orMap in the Examples class.

We first write down the template for the case we already know -- the one where the loop uses the Traversal iterator. As we have done in class, we start by converting the recursive method into a form that uses the accumulator to keep track of the knowledge we already have, and passes that information to the next recursive invocation.

Read carefully the Template Analysis and make sure you understand the meaning of all parts.

Last modified: Thursday, November 9th, 2006 11:07:05pm