Java 集合 自定义ArrayList
package array;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Spliterator;
import java.util.function.Consumer;
public class MyArrayList<E> {
private static final int DEFAULT_CAPACITY = 10;
private int theSize;
private E[] theItems;
public MyArrayList() {
doClear();
}
public boolean isEmpty() {
return theSize == 0;
}
public void trimToSize() {
ensureCapacity(size());
}
public E get(int index) {
if (index < 0 || index >= size()) {
throw new ArrayIndexOutOfBoundsException();
}
return theItems[index];
}
public E set(int index, E newVal) {
if (index < 0 || index >= size()) {
throw new ArrayIndexOutOfBoundsException();
}
E old = theItems[index];
theItems[index] = newVal;
return old;
}
public boolean add(E val) {
this.add(size(), val);
return true;
}
public void add(int index, E val) {
if (theItems.length == size()) {
ensureCapacity(size() * 2 + 1);
}
for (int i = theSize; i > index; i--) {
theItems[i] = theItems[i - 1];
}
theItems[index] = val;
theSize++;
}
public E remove(int index) {
E removedItem = theItems[index];
for (int i = index; i < size() - 1; i++) {
theItems[index] = theItems[index + 1];
}
theSize--;
return removedItem;
}
public void ensureCapacity(int newCapacity) {
if (newCapacity < theSize) {
return;
}
E[] newItems = (E[]) new Object[newCapacity];
for (int i = 0; i < size(); i++) {
newItems[i] = theItems[i];
}
theItems = newItems;
}
public int size() {
return theSize;
}
private void doClear() {
theSize = 0;
ensureCapacity(DEFAULT_CAPACITY);
}
public Iterator<E> iterator(){
return new ArrayListIterator();
}
private class ArrayListIterator implements Iterator<E> {
private int current = 0;
@Override
public boolean hasNext() {
return current < size();
}
@Override
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return theItems[current++];
}
@Override
public void remove() {
MyArrayList.this.remove(current--);
}
}
}