CS 161 Lab 3

Overview

This lab will explore the ArrayList data structure as well as the following aspects of OO programming in Java: The ArrayList structure in java is a way to create an array that can grow or shrink in size during the execution of a program. It means that items can be added and removed from the list. An Array on the other hand, has a fixed size: once we declared it to be a particular size, that size cannot be changed.
To set up an ArrayList, you first have to import the package from the java.util library:
import java.util.ArrayList;
You can then create a new ArrayList object:
ArrayList listTest = new ArrayList( );
The Java API has a list of all the methods provided by an ArrayList. See: Java ArrayList API.

Lab Assignment

Please complete this lab individually. You are always welcome to bring any lab material and questions to office hours. We will use Animal.java and GuinnessBook.java. Please download the following files:

Assignment Overview

Previously, you have used arrays to store and manipulate collections of primitives and objects. However, Java arrays can only represent collections of a fixed size. This is a limitation as the programmer often does not know how many items will need to be stored in advance.

Many programming languages, including Java, provide programmers with array-like data structures that are resizable. In Java, this data structure is ArrayList. An ArrayList internally maintains an array of data that is resized to accomodate additional elements. ArrayList also allows the programmer to add/remove items at arbitrary indices and even find the index of a particular item.

Complete the implementation of Animal.java, by adding the following methods:

When implementing constructors, getters/setters, toString or equals methods you can use Eclipse to help you write those methods - under the "Source" tab of Eclipse there are options for generating stubs for those methods.

In GuinnessBook.java:
  • Complete the code for the constructor. You just need to add code that adds the animals to the landAnimals arrayList.
  • The toString() method. This can make use of Animal's toString()method. It should return a string representation all of the elements in the arrayList. EX:

    Name: giraffe Top Speed: 32
    Name: pronghorn Top Speed: 61
    Name: reindeer Top Speed: 32

  • Test your code in the main method.
  • Follow the instructions in main and testGuinnessBook

    Grading

    This lab is worth a total of 2 points broken down as:
    Demo/Attendance: 1 point
    Effort: 1 point