仿照JDK编写一个简化的ArrayList实现是一个很好的学习Java集合框架内部工作原理的方式。以下是一个简化版的ArrayList实现,它包含了基本的添加、获取、删除和大小检查功能。
public class MyArrayList<E> {
private static final int DEFAULT_CAPACITY = 10;
private Object[] elements;
private int size; public MyArrayList() {
this(DEFAULT_CAPACITY);
} public MyArrayList(int initialCapacity) {
if (initialCapacity < 0) {
throw new IllegalArgumentException("Initial capacity must be non-negative");
}
elements = new Object[initialCapacity];
size = 0;
} public int size() {
return size;
} public boolean isEmpty() {
return size == 0;
} public void add(E e) {
ensureCapacity(size + 1);
elements[size] = e;
size++;
} public E get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsEx