简易的ArrayList容器
代码如下
package container;
import java.util.Objects;
import java.util.function.Consumer;
public class ArrList<E> {
private int size;
private Object[] data;
private static final Object[] EMPTY_DATA = {};
private int cur;
private static final int DEFAULT_CAPACITY = 10;
ArrList() {
initCapacity(DEFAULT_CAPACITY);
}
@SuppressWarnings("unchecked")
private void initCapacity(int newCapacity) {
data = data == null ? (E[]) EMPTY_DATA : data;
E[] old = (E[]) data;
data = new Object[newCapacity];
if (size >= 0) System.arraycopy(old, 0, data, 0, size);
}
private int size() {
return size;
}
void add(E e) {
if (size() == data.length) {
initCapacity(size + size >> 1);
}
data[size++] = e;
}
void add(int index, E e) {
check(index);
if (size == data.length) {
initCapacity(size + size >> 1);
}
System.arraycopy(data, index, data, index + 1, size - index);
data[index] = e;
size++;
}
private void check(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("index err : " + index);
}
}
boolean isEmpty() {
return size == 0;
}
E remove(int index) {
E e = get(index);
System.arraycopy(data, index + 1, data, index, size - index - 1);
size--;
return e;
}
@SuppressWarnings("unchecked")
E get(int index) {
check(index);
return (E) data[index];
}
void forEach(Consumer<Object> action) {
Objects.requireNonNull(action);
for (int i = 0; i < size; i++) {
action.accept(data[i]);
}
}
boolean hasNext() {
return cur != size;
}
E next() {
return get(cur++);
}
}