Solution to MyArrayList practice problem

Complete the MyArrayList practice problem before reviewing the solution.

Review the MyArrayList solution with AP CS Tutor Brandon Horn.

There is no method documentation because the methods are intended to work in exactly the same way as the java.util.ArrayList class. Throwing exceptions is not part of the AP Computer Science A subset and is not included on the exam.

public class MyArrayList<E>
{
  private Object[] a;
  private int size;

  public MyArrayList()
  {
    this(10);
  }

  public MyArrayList(int initialCapacity)
  {
    if (initialCapacity < 0)
      throw new IllegalArgumentException();

    a = new Object[initialCapacity];
    size = 0;
  }

  public int size()
  {
    return size;
  }

  public E get(int index)
  {
    if (index < 0 || index >= size)
      throw new IndexOutOfBoundsException();

    return (E) a[index];
  }

  public E set(int index, E element)
  {
    if (index < 0 || index >= size)
      throw new IndexOutOfBoundsException();

    Object old = a[index];
    a[index] = element;
    return (E) old;
  }

  public boolean contains(Object elem)
  {
    for (int i = 0; i < size; i++)
    {
      if((elem == null && a[i] == null) ||
         (elem != null && elem.equals(a[i])))
        return true;
    }
    return false;
  }

  public void trimToSize()
  {
    if (size < a.length)
    {
      Object[] b = new Object[size];

      for(int i = 0; i < size; i++)
        b[i] = a[i];

      a = b;
    }
  }

  public void add(E elem)
  {
    add(size, elem);
  }

  public void add(int index, E element)
  {
    if (index < 0 || index > size)
      throw new IndexOutOfBoundsException();

    if (size < a.length)
    {
      for(int i = size - 1; i >= index; i--)
        a[i + 1] = a[i];
    }
    else
    {
      Object[] b = new Object[a.length * 2 + 1];

      for(int i = 0; i < index; i++)
        b[i] = a[i];

      for(int i = index; i < size; i++)
        b[i + 1] = a[i];

      a = b;
    }

    a[index] = element;
    size++;
  }

  public E remove(int index)
  {
    if (index < 0 || index >= size)
      throw new IndexOutOfBoundsException();

    Object old = a[index];

    for(int i = index + 1; i < size; i++)
      a[i - 1] = a[i];

    a[size - 1] = null;
    size--;
    return (E) old;
  }

  public boolean remove(Object elem)
  {
    for (int i = 0; i < size; i++)
    {
      if((elem == null && a[i] == null) ||
         (elem != null && elem.equals(a[i])))
      {
        remove(i);
        return true;
      }
    }
    return false;
  }
}

Get AP CS Help

Leave a Reply