写个ArrayList源码
时间: 2023-06-03 14:02:09 浏览: 91
好的,以下是 ArrayList 的简化源码:
public class ArrayList<E> {
private Object[] elementData;
private int size;
public ArrayList() {
this(10); // 默认初始容量为 10
}
public ArrayList(int initialCapacity) {
if (initialCapacity < 0) {
throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
}
this.elementData = new Object[initialCapacity];
}
public boolean add(E e) {
ensureCapacity(size + 1);
elementData[size++] = e;
return true;
}
public E get(int index) {
rangeCheck(index);
return (E) elementData[index];
}
public int size() {
return size;
}
private void ensureCapacity(int minCapacity) {
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity < minCapacity) {
newCapacity = minCapacity;
}
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
private void rangeCheck(int index) {
if (index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
}
}
注意:以上代码为简化版 ArrayList 源码,实际源码会更加复杂。
阅读全文