ArrayDeque 中实现无限大小的关键在于通过数组备份的方式来存储数据,当数组容量不足时,会创建一个新的更大的数组,将数据从旧数组复制到新数组。具体代码示例如下:
public class ArrayDeque {
private Object[] elements;
private int head;
private int tail;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
public ArrayDeque() {
elements = new Object[DEFAULT_INITIAL_CAPACITY];
}
// 添加元素到队列尾部
public void addLast(E e) {
if (tail == elements.length) {
// 如果数组容量不足,则创建新数组
grow();
}
elements[tail++] = e;
}
// 扩容数组
private void grow() {
int oldCapacity = elements.length;
int newCapacity = oldCapacity * 2;
Object[] newElements = new Object[newCapacity];
// 将旧数组中的元素复制到新数组中
System.arraycopy(elements, head, newElements, 0, tail - head);
elements = newElements;
head = 0;
tail = oldCapacity;
}
}
上面代码中的 grow()
方法用于当数组容量不足时扩容数组,同时将旧数组中的元素复制到新数组中。这样就可以实现在 ArrayDeque 中无限存储元素的效果。