add indexOf and lastIndexOf methods to java.util.List

This commit is contained in:
Joel Dice 2009-08-04 17:58:31 -06:00
parent 0a7f94abfe
commit 590238bbfc
5 changed files with 49 additions and 5 deletions

View File

@ -94,7 +94,7 @@ public class ArrayList<T> extends AbstractList<T> {
return true;
}
public int indexOf(T element) {
public int indexOf(Object element) {
for (int i = 0; i < size; ++i) {
if (equal(element, array[i])) {
return i;
@ -103,8 +103,8 @@ public class ArrayList<T> extends AbstractList<T> {
return -1;
}
public int lastIndexOf(T element) {
for (int i = size; i >= 0; --i) {
public int lastIndexOf(Object element) {
for (int i = size - 1; i >= 0; --i) {
if (equal(element, array[i])) {
return i;
}

View File

@ -73,6 +73,24 @@ public class Arrays {
return false;
}
public int indexOf(Object element) {
for (int i = 0; i < array.length; ++i) {
if (equal(element, array[i])) {
return i;
}
}
return -1;
}
public int lastIndexOf(Object element) {
for (int i = array.length - 1; i >= 0; --i) {
if (equal(element, array[i])) {
return i;
}
}
return -1;
}
public T get(int index) {
return array[index];
}

View File

@ -93,6 +93,28 @@ public class LinkedList<T> extends AbstractSequentialList<T> {
return find(element) != null;
}
public int indexOf(Object element) {
int i = 0;
for (Cell<T> c = front; c != null; c = c.next) {
if (equal(c.value, element)) {
return i;
}
++ i;
}
return -1;
}
public int lastIndexOf(Object element) {
int i = size;
for (Cell<T> c = rear; c != null; c = c.prev) {
-- i;
if (equal(c.value, element)) {
return i;
}
}
return -1;
}
public boolean add(T element) {
addLast(element);
return true;

View File

@ -21,6 +21,10 @@ public interface List<T> extends Collection<T> {
public void add(int index, T element);
public int indexOf(Object value);
public int lastIndexOf(Object value);
public boolean isEmpty();
public ListIterator<T> listIterator(int index);

View File

@ -93,11 +93,11 @@ public class Vector<T> extends AbstractList<T> {
list.clear();
}
public synchronized int indexOf(T element) {
public synchronized int indexOf(Object element) {
return list.indexOf(element);
}
public synchronized int lastIndexOf(T element) {
public synchronized int lastIndexOf(Object element) {
return list.lastIndexOf(element);
}