在Java中自我实现ArrayList需要实现List接口并且处理好数据的动态增长。以下是一个简单的自我实现ArrayList的例子:
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class MyArrayList<E> implements Iterable<E> {
private static final int DEFAULT_CAPACITY = 10;
private int size;
private Object[] elements;
public MyArrayList() {
elements = new Object[DEFAULT_CAPACITY];
size = 0;
}
private void ensureCapacity() {
if (size >= elements.length) {
elements = Arrays.copyOf(elements, 2 * elements.length);
}
}
public void add(E element) {
ensureCapacity();
elements[size++] = element;
}
public E get(int index) {
if (index >= size) {
throw new IndexOutOfBoundsException();
}
return (E) elements[index];
}
public int size() {
return size;
}
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
private int current = 0;
private int expectedModCount = size;
@Override
public boolean hasNext() {
return current < size;
}
@Override
public E next() {
if (current >= size) {
throw new NoSuchElementException();
}
if (expectedModCount != size) {
throw new ConcurrentModificationException();
}
return (E) elements[current++];
}
};
}
}
这个自我实现的ArrayList包含了基本的功能,如增加元素、获取元素和获取大小。它还实现了Iterable接口,允许对列表进行迭代。在迭代器内部,我们使用expectedModCount
来检测列表结构是否在迭代过程中发生了改变,如果改变了,则抛出ConcurrentModificationException
异常。这是为了保证迭代过程的一致性。