CS 145 Lecture 40 – Implementing ArrayList
Agenda
- what ?s
- rolling our own ArrayList
- evaluations
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?
I fill to the full
Then do I double in size
How big can I be?