此方法参照了《数据结构与算法分析,java语言描述》
顺序表实现
接口分析
接口1
Iterable<AnyType>
此接口来自于java.lang.iterable
接口定义的方法
iterator
Iterator<T> iterator()
返回一个在一组 T 类型的元素上进行迭代的迭代器。
返回:
一个迭代器。
接口2
java.util.Iterator<AnyType>
接口定义的方法
hasNext
boolean hasNext()
如果仍有元素可以迭代,则返回 true。(换句话说,如果 next 返回了元素而不是抛出异常,则返回 true)。
返回:
如果迭代器具有多个元素,则返回 true。
next
E next()
返回迭代的下一个元素。
返回:
迭代的下一个元素。
抛出:
NoSuchElementException - 没有元素可以迭代。
remove
void remove()
从迭代器指向的 collection 中移除迭代器返回的最后一个元素(可选操作)。每次调用 next 只能调用一次此方法。如果进行迭代时用调用此方法之外的其他方式修改了该迭代器所指向的 collection,则迭代器的行为是不确定的。
抛出:
UnsupportedOperationException - 如果迭代器不支持 remove 操作。
IllegalStateException - 如果尚未调用 next 方法,或者在上一次调用 next 方法之后已经调用了 remove 方法。
public class MyArrayList<AnyType> implements Iterable<AnyType> {
//默认容量为10
private static final int DEFAULT_CAPACITY = 10;
private int theSize;
private AnyType [] theItems;
//初始化list
public MyArrayList() {
clear();
}
//设定初始尺寸,和缓冲区大小
public void clear() {
theSize = 0;
ensureCapacity( DEFAULT_CAPACITY );
}
//返回现在的列表大小
public int size() {
return theSize;
}
//列表为空返回true,否则返回false
public boolean isEmpty() {
return size() == 0;
}
//设置缓冲区大小
public void trimToSize() {
ensureCapacity( size() );
}
//得到索引对象,错误则弹出索引错误
public AnyType get(int index) {
if (index < 0 || index >= size())
//throw 类似于python的raise用法
throw new ArrayIndexOutOfBoundsException();
return theItems[index];
}
//为列表按索引加入新的对象
public AnyType set(int index, AnyType newValue) {
if (index <