Here is the code we wrote today. First the methods in OurLinkedList.java:
public T get(int index) {
if((index < 0) || (index >= size()))
throw new IndexOutOfBoundsException();
Node curr = head;
for(int i=0; i < index; i++)
curr = curr.next;
return curr.value;
}
//INCOMPLETE; DOESN'T FULLY WORK:
public boolean remove(T item) {
//remove item from list if it's there; return whether it was
Node curr = head; //current node
Node prev = null; //node before current one
while(curr != null) {
if(curr.value.equals(item)) {
prev.next = curr.next;
return true;
}
prev = curr; //advance the references
curr = curr.next;
}
return false;
}
Then the code in OurArrayList.java:
public T get(int index) {
if(index >= num)
throw new IndexOutOfBoundsException();
return vals[index];
}
Then the testing code in TestOurList.java:
@Test
public void testGetExceptions() {
list.add("A");
list.add("B");
list.add("C");
//throws exception if index < 0
try {
list.get(-1);
fail();
} catch(IndexOutOfBoundsException ex) {
//DO NOTHING; exception should be thrown
}
//throws exception if index is too big
try {
list.get(3);
fail();
} catch(IndexOutOfBoundsException ex) {
//DO NOTHING; exception should be thrown
}
}
@Test
public void testGetValid() {
list.add("A");
list.add("B");
list.add("C");
//returns value at the given index
assertEquals("A", list.get(0));
assertEquals("B", list.get(1));
assertEquals("C", list.get(2));
}
@Test
public void size() {
assertEquals(0, list.size());
list.add("Hi");
list.add("Hello");
list.add("CS 142");
list.add("Class");
assertEquals(4, list.size());
}
@Test
public void addMany() {
for(int i=0; i < 10000; i++)
list.add("item " + i);
assertEquals(10000, list.size());
assertEquals("item 5639", list.get(5639));
}