teaching machines

CS 145 Lecture 40 – Implementing ArrayList

December 8, 2014 by . Filed under cs145, fall 2014, lectures.

Agenda

Code

StringList.java

package lecture1208;

public class StringList {
  private String[] items;
  private int nItems;
  
  public StringList() {
    items = new String[10];
    nItems = 0;
  }
  
  public int size() {
    return nItems;
  }
  
  public String get(int i) {
    if (i < 0 || i >= nItems) {
      throw new IndexOutOfBoundsException("Bad index " + i);
    }
    return items[i];
  }
  
  public void add(String s) {
    if (nItems == items.length) {
      doubleCapacity();
    }
    items[nItems] = s;
    ++nItems;
  }
  
  private void doubleCapacity() {
    String[] moreItems = new String[items.length * 2];
    for (int i = 0; i < items.length; ++i) {
      moreItems[i] = items[i];
    }
    items = moreItems;
  }
}

Haiku

a riddle:
I fill to the full
Then do I double in size
How big can I be?