CS 241 Data Structures- Lab 3 -- ArrayList, Due 2/21

This lab won't take much time; once you understand it... You may work on this lab with a partner if you wish; make sure to tell me when you demo if so! But, it is your responsibility to be sure both of you understand how it all works (since the midterm will be written to test the lab content)!

Overview

For this lab, you will implement your own version of a very simplified version of ArrayList<T>; i.e. a generic list with the following methods:

Approach

Start with this code:
public class MyArrayListThang {

    public static void main(String[] args) {
        MyArrayList<Integer> list = new MyArrayList();

        for (int i = 0; i < 10; i++) {
            list.add(43 + i);
        }

        display(list);
        
        //list.add(4);  // overfills!
    }

    private static void display(MyArrayList list) {
        for (int i = 0; i < list.size(); i++) {
            System.out.println("list.get(" + i + ") = " + list.get(i));
        }
    }
        
...and...
public class MyArrayList<T> {

    final static int INITIAL_CAPACITY = 10;
    Object[] list;
    int last;
    int capacity;

    MyArrayList() {
        list = new Object[10];
        last = -1;
        capacity = INITIAL_CAPACITY;
    }

    T get(int i) {
        return (T) list[i];
    }

    void add(T nuOne) {
        if (size() >= capacity) {
            doubleCapacity();
        }
        
        list[++last] = nuOne;  // you know there is space now!
    }

    public int size() {
        return last + 1;
    }

    private void doubleCapacity() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}
        
As you can see, the list starts with room for 10 elements. When the user adds the 11th, it should double the capacity (so you will need to allocate a bigger array, and copy the elements of the current array into it).

How to get credit

  1. Demo your program in lab by the due date. Make sure it is easy for a user (who is not you!) to tell if it is working correctly.

Extra credit

  1. Implement boolean contains (T findMe)
  2. Implement other standard ArrayList methods