3.4 MyArrayList 类的实现
3.4 MyArrayList 类的实现
这节提供一个便于使用的 MyArrayList 泛型类的实现,这里不检测可能使得迭代器无效的结构上的修改,也不检测非法的迭代器 remove 方法。
- MyArrayList 将保持基础数组,数组的容量,以及存储在MyArrayList 中的当前项数。
- MyArrayList 将提供一种机制以改变基础数组的容量。通过获得一个新数组,将老数组拷贝到新数组中来改变数组的容量,允许虚拟机回收老数组。
- MyArrayList 将提供 get 和 set 的实现。
- MyArrayList 将提供基本的例程,如 size 、isEmpty 和 clear,它们是典型的单行程序;还提供 remove,以及两种不同版本的 add。如果数组大小和容量相同,那么这两个 add 例程将增加容量。
- MyArrayList 将提供一个实现 Iterator 接口的类。这个类将储存迭代序列中的下一项的下标,并提供 next、hasNext 和 remove 等方法的实现。MyArrayList 的迭代器方法直接返回实现 Iterator 接口的该类的新构造的实例。
public class MyArrayList<E> implements Iterable<E> {
public static final int DEFAULT_CAPACITY = 10;//默认数组长度
private int theSize;
private E[] theItems;
public MyArrayList() {
doClear();
}
public void clear() {
doClear();
}
private void doClear() {
theSize = 0;
ensureCapacity(DEFAULT_CAPACITY);
}
public int size() {
return theSize;
}
public boolean isEmpty() {
return theSize == 0;
}
public void trimToSize() {//将当前数组复制到一个大小刚好合适的数组中
ensureCapacity(theSize);
}
public E get(int idx) {
if (idx < 0 || idx >= theSize) {
throw new ArrayIndexOutOfBoundsException();
}
return theItems[idx];
}
public E set(int idx, E newVal) {
if (idx < 0 || idx >= theSize) {
throw new ArrayIndexOutOfBoundsException();
}
E old = theItems[idx];
theItems[idx] = newVal;
return old;
}
public void ensureCapacity(int newCapacity) {
if (newCapacity < theSize) {
return;
}
E[] old = theItems;
theItems = (E[]) new Object[newCapacity];
for (int i = 0; i < theSize; i++) {
theItems[i] = old[i];
}
}
public boolean add(E x) {
add(theSize, x);
return true;
}
public void add(int idx, E x) {
if (theItems.length == theSize) {
ensureCapacity(theSize * 2 + 1);//+1应对大小为0时的情况
}
for (int i = theSize; i > idx; i--) {
theItems[i] = theItems[i - 1];
}
theItems[idx] = x;
theSize++;
}
public E remove(int idx) {
E removedItem = theItems[idx];
for (int i = idx; i < theSize; i++) {
theItems[i] = theItems[i + 1];
}
theSize--;
return removedItem;
}
public Iterator<E> iterator() {
return new ArrayListIterator();
}
private class ArrayListIterator implements Iterator<E> {
private int current = 0;
public boolean hasNext() {
return current < size();
}
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return theItems[current++];
}
public void remove() {
MyArrayList.this.remove(--current);
}
}
}
ArrayListIterator 是 MyArrayList 的内部类,可以直接访问 MyArrayList 的 private 实例

浙公网安备 33010602011771号