在 Java 中,如何实现一个自定义的 List 接口?请提供一个示例代码并说明其具体实现逻辑。
在 Java 中,可以通过实现 List 接口来自定义一个 List。List 接口是 Java 集合框架的一部分,定义了一系列操作有序集合的方法。以下是实现自定义 List 的详细步骤和示例代码。
实现逻辑
- 实现
List接口:List接口包含了许多方法,比如add,remove,get等。我们需要为这些方法提供具体的实现。 - 使用底层数据结构:通常可以使用数组或链表来存储元素。在示例中,我们使用动态数组作为底层存储结构。
- 动态扩容:当数组长度不足以存储更多元素时,需要动态扩展数组的容量。
- 支持泛型:为了让自定义
List可以存储任意类型的元素,应使用泛型。 - 异常处理:在实现过程中,需要处理
IndexOutOfBoundsException等异常情况。
示例代码
以下是一个基于动态数组实现的自定义 List 示例:
import java.util.*;
public class CustomArrayList<E> implements List<E> {
private static final int DEFAULT_CAPACITY = 10;
private Object[] elements;
private int size;
// 构造方法
public CustomArrayList() {
this.elements = new Object[DEFAULT_CAPACITY];
this.size = 0;
}
// 添加元素
@Override
public boolean add(E element) {
ensureCapacity(size + 1);
elements[size++] = element;
return true;
}
// 在指定位置添加元素
@Override
public void add(int index, E element) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
ensureCapacity(size + 1);
System.arraycopy(elements, index, elements, index + 1, size - index);
elements[index] = element;
size++;
}
// 获取指定位置的元素
@Override
public E get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
return (E) elements[index];
}
// 移除指定位置的元素
@Override
public E remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
E oldValue = (E) elements[index];
int numMoved = size - index - 1;
if (numMoved > 0) {
System.arraycopy(elements, index + 1, elements, index, numMoved);
}
elements[--size] = null; // 释放引用
return oldValue;
}
// 获取 List 的大小
@Override
public int size() {
return size;
}
// 动态扩容
private void ensureCapacity(int minCapacity) {
if (minCapacity > elements.length) {
int newCapacity = elements.length * 2;
if (newCapacity < minCapacity) {
newCapacity = minCapacity;
}
elements = Arrays.copyOf(elements, newCapacity);
}
}
// 其他方法暂未实现
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
private int cursor = 0;
@Override
public boolean hasNext() {
return cursor < size;
}
@Override
public E next() {
if (cursor >= size) {
throw new NoSuchElementException();
}
return (E) elements[cursor++];
}
};
}
@Override
public Object[] toArray() {
return Arrays.copyOf(elements, size);
}
@Override
public <T> T[] toArray(T[] a) {
if (a.length < size) {
return (T[]) Arrays.copyOf(elements, size, a.getClass());
}
System.arraycopy(elements, 0, a, 0, size);
if (a.length > size) {
a[size] = null;
}
return a;
}
@Override
public boolean remove(Object o) {
int index = indexOf(o);
if (index >= 0) {
remove(index);
return true;
}
return false;
}
@Override
public boolean containsAll(Collection<?> c) {
for (Object o : c) {
if (!contains(o)) {
return false;
}
}
return true;
}
@Override
public boolean addAll(Collection<? extends E> c) {
boolean modified = false;
for (E e : c) {
if (add(e)) {
modified = true;
}
}
return modified;
}
@Override
public boolean addAll(int index, Collection<? extends E> c) {
boolean modified = false;
for (E e : c) {
add(index++, e);
modified = true;
}
return modified;
}
@Override
public boolean removeAll(Collection<?> c) {
boolean modified = false;
for (Object o : c) {
while (remove(o)) {
modified = true;
}
}
return modified;
}
@Override
public boolean retainAll(Collection<?> c) {
boolean modified = false;
for (int i = 0; i < size; i++) {
if (!c.contains(elements[i])) {
remove(i--);
modified = true;
}
}
return modified;
}
@Override
public void clear() {
for (int i = 0; i < size; i++) {
elements[i] = null;
}
size = 0;
}
@Override
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++) {
if (elements[i] == null) {
return i;
}
}
} else {
for (int i = 0; i < size; i++) {
if (o.equals(elements[i])) {
return i;
}
}
}
return -1;
}
@Override
public int lastIndexOf(Object o) {
if (o == null) {
for (int i = size - 1; i >= 0; i--) {
if (elements[i] == null) {
return i;
}
}
} else {
for (int i = size - 1; i >= 0; i--) {
if (o.equals(elements[i])) {
return i;
}
}
}
return -1;
}
@Override
public ListIterator<E> listIterator() {
return new ListIterator<E>() {
private int cursor = 0;
@Override
public boolean hasNext() {
return cursor < size;
}
@Override
public E next() {
if (cursor >= size) {
throw new NoSuchElementException();
}
return (E) elements[cursor++];
}
@Override
public boolean hasPrevious() {
return cursor > 0;
}
@Override
public E previous() {
if (cursor <= 0) {
throw new NoSuchElementException();
}
return (E) elements[--cursor];
}
@Override
public int nextIndex() {
return cursor;
}
@Override
public int previousIndex() {
return cursor - 1;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public void set(E e) {
if (cursor <= 0 || cursor > size) {
throw new IllegalStateException();
}
elements[cursor - 1] = e;
}
@Override
public void add(E e) {
CustomArrayList.this.add(cursor++, e);
}
};
}
@Override
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
return new ListIterator<E>() {
private int cursor = index;
@Override
public boolean hasNext() {
return cursor < size;
}
@Override
public E next() {
if (cursor >= size) {
throw new NoSuchElementException();
}
return (E) elements[cursor++];
}
@Override
public boolean hasPrevious() {
return cursor > 0;
}
@Override
public E previous() {
if (cursor <= 0) {
throw new NoSuchElementException();
}
return (E) elements[--cursor];
}
@Override
public int nextIndex() {
return cursor;
}
@Override
public int previousIndex() {
return cursor - 1;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public void set(E e) {
if (cursor <= 0 || cursor > size) {
throw new IllegalStateException();
}
elements[cursor - 1] = e;
}
@Override
public void add(E e) {
CustomArrayList.this.add(cursor++, e);
}
};
}
@Override
public List<E> subList(int fromIndex, int toIndex) {
if (fromIndex < 0 || toIndex > size || fromIndex > toIndex) {
throw new IndexOutOfBoundsException();
}
List<E> subList = new CustomArrayList<>();
for (int i = fromIndex; i < toIndex; i++) {
subList.add((E) elements[i]);
}
return subList;
}
}
代码说明
- 底层数据结构:
CustomArrayList使用一个Object[]数组来存储元素,并通过size变量记录当前元素数量。 - 动态扩容:
ensureCapacity方法用于在数组容量不足时扩展数组长度。 - 方法覆盖:示例中实现了
List接口的核心方法,如add,remove,get,size等,并处理了可能的异常情况。 - 泛型支持:通过泛型
E,CustomArrayList可以存储任意类型的对象。 - 迭代器实现:
iterator和listIterator方法返回的迭代器支持遍历操作。
总结
通过实现 List 接口,我们可以自定义一个功能完整的 List。在实际应用中,还可以根据需求进一步优化性能或扩展功能。