import java.util.Iterator;
import java.util.NoSuchElementException;
public class MyArrayList<T> implements Iterable<T> {
public static final int INITIAL_CAPACITY = 10;
private int theSize;
private T[] items;
public MyArrayList() {
clear();//由于构造方法和clear()方法的实现一样,所以此处调用clear方法
}
public int size() {
return theSize;
}
public boolean isEmpty() {
return size() == 0;//对于返回类型为boolean的方法,有时只需直接将逻辑表达式写在return后面即可
}
/**
* 删掉所有元素,容量设为初始大小
*/
public void clear() {
theSize = 0;
extendCapacity(INITIAL_CAPACITY);
}
public boolean add(T item) {//追加元素为插入元素的一种特殊情况
insert(size(), item);
return true;
}
public void insert(int index, T item) {
if(size() == items.length)
extendCapacity(size() * 2 + 1);
for(int i = theSize; i > index; i--)
items[i] = items[i-1];
items[index] = item;
theSize++;
}
public T remove(int index) {
if(index<0 || index>= size())
return null;
T old = items[index];//先将要删除的元素保存下来,以便后续返回
for (int i = index; i < size()-1; i++) {
items[i] = items[i+1];
}
theSize--;
return old;
}
public void extendCapacity(int newCapacity) {
T[] oldItems = items;//先将原本的元素保存下来,防止下一步新建数组时元素被覆盖
items = (T[]) new Object[newCapacity];
for (int i = 0; i < size(); i++) {
items[i] = oldItems[i];
}
}
public T get(int index) {
if(index<0 || index>= size())
throw new IndexOutOfBoundsException();
return items[index];
}
public T set(int index, T item) {
if(index<0 || index>= size())
throw new IndexOutOfBoundsException();
T old = items[index];//先将被替换的元素保存下来,以便后续返回
items[index] = item;
return old;
}
@Override
public Iterator<T> iterator() {
return new MyIterator();
}
private class MyIterator implements Iterator<T>{//将迭代器定义为内部类,以便能够使用MyArrayList中的私有变量
private int current = 0;
@Override
public boolean hasNext() {
return current < size();
}
@Override
public T next() {
if(!hasNext())
throw new NoSuchElementException();
return items[current++];
}
@Override
public void remove() {
MyArrayList.this.remove(--current);//由于获取下一个元素时current+1,所以要想删除获取的元素,需要先将current-1
}
}
}