List now implements various forms of add()

This commit is contained in:
Eric Scharff 2007-09-26 10:32:39 -06:00
parent 219e381def
commit 4d3fd38d54
5 changed files with 29 additions and 0 deletions

View File

@ -67,6 +67,13 @@ public class ArrayList<T> implements List<T> {
return false;
}
public void add(int index, T element) {
size = Math.max(size+1, index+1);
grow();
System.arraycopy(array, index, array, index+1, size-index);
array[index] = element;
}
public boolean add(T element) {
++ size;
grow();

View File

@ -25,6 +25,10 @@ public class Arrays {
throw new UnsupportedOperationException();
}
public void add(int index, T element) {
throw new UnsupportedOperationException();
}
public boolean contains(T element) {
for (int i = 0; i < array.length; ++i) {
if (equal(element, array[i])) {

View File

@ -107,6 +107,16 @@ public class LinkedList<T> implements List<T> {
return true;
}
public void add(int index, T element) {
if (index == 0) {
addFirst(element);
} else {
Cell<T> cell = find(index);
Cell<T> newCell = new Cell<T>(element, cell.prev, cell);
cell.prev.next = newCell;
}
}
public void addFirst(T element) {
addFirst(new Cell(element, null, null));
}

View File

@ -5,6 +5,10 @@ public interface List<T> extends Collection<T> {
public T remove(int index);
public boolean add(T element);
public void add(int index, T element);
public boolean isEmpty();
public <S> S[] toArray(S[] a);

View File

@ -26,6 +26,10 @@ public class Vector<T> implements List<T> {
return list.contains(element);
}
public synchronized void add(int index, T element) {
list.add(index, element);
}
public synchronized boolean add(T element) {
return list.add(element);
}