public class MyArrayList<AnyType extends Comparable<? super AnyType>> implements Iterable<AnyType>{
//默认新建数组大小
private static final int DEFAULT_CAPACITY = 10;
//表中元素个数
private int theSize;
private AnyType[] theItems;
//数组初始化
private void doClear() {
theSize = 0;
ensureCapacity(DEFAULT_CAPACITY);
}
//设置一个容量更大的数组并将原数组内容复制
private void ensureCapacity(int newCapacity) {
if(newCapacity < theSize)
return;
else {
AnyType[] old = theItems;
theItems = (AnyType[]) new Object[newCapacity];
for(int i = 0; i < theSize; i++) {
theItems[i] = old[i];
}
}
}
//
public void clear() {
doClear();
}
//返回表中元素个数
public int size() {
return theSize;
}
public boolean isEmpty() {
return theSize == 0;
}
public AnyType get(int i) {
if(i < 0 || i >= theSize) {
throw new ArrayIndexOutOfBoundsException();
}
else {
return theItems[i];
}
}
public AnyType set(int i, AnyType newVal) {
if(i < 0 || i >= theSize) {
throw new ArrayIndexOutOfBoundsException();
}
else {
AnyType oldVal = theItems[i];
theItems[i] = newVal;
return oldVal;
}
}
public void add() {
if(theSize + 1 < theItems.length) {
ensureCapacity(theSize * 2);
}
}
//默认无参构造
public MyArrayList() {
doClear();
}
@Override
public java.util.Iterator<AnyType> iterator(){
return new ArrayIterator();
}
//内部类迭代器
private class ArrayIterator implements java.util.Iterator<AnyType>{
private int index = 0;
@Override
public boolean hasNext() {
if(index + 1 < theSize) {
return true;
}
else{
return false;
}
}
@Override
public AnyType next() {
if(hasNext()) {
return theItems[index++];
}
else {
return null;
}
}
}
}
内部类实现迭代器