Here is the code we wrote today. This our OurArrayList.java:
public class OurArrayList< T> {
private T[] vals; //storage for the list values
private int num; //number of values in the list
@SuppressWarnings("unchecked")
public OurArrayList() { //create empty list
num = 0;
vals = (T[]) new Object[3];
}
public int size() { //return number of values in the list
return num;
}
@SuppressWarnings("unchecked")
public void add(T item) { //add item to end of the list
if(num == vals.length) { //if array is full, double its size
T[] other = (T[]) new Object[num*2];
for(int i=0; i < num; i++)
other[i] = vals[i];
vals = other;
}
vals[num] = item;
num++;
}
public boolean contains(T item) { //return whether item is in list
for(int i=0; i < num; i++)
if(vals[i].equals(item))
return true;
return false;
}
}
And here is Main.java:
public class Main {
public static void main(String[] args) {
OurArrayList< String> list = new OurArrayList< String>();
System.out.println(list.size());
list.add("hi");
System.out.println(list.size());
list.add("hi2");
list.add("hello");
list.add("cs142");
list.add("yo");
}
}