集合类的基本接口是Collection接口,这个接口的两个基本方法是
public interface Collection<E>
{
boolean add(E element);
Iterator<E> iterator();
}
Iterator接口包含3个方法
public interface Iterator<E>
{
E next();
boolean hasNext();
void remove();
}
next方法到达集合末尾时将抛出NoSuchElementException,所以调用next之前应先调用hasNext方法。
"for each"可以与任何实现了Iterable接口的对象一起工作,Collection接口扩展了Iterable接口,所以标准库中任何集合类都可以使用"for each"。
Java迭代器可认为是位于两个元素之间。调用next时,迭代器越过下一个元素,并返回刚刚越过的那个元素的引用。调用remove时,删除上次调用next时越过的元素。
//删除字符串集合的第一个元素
Iterator<String> it = c.iterator();
it.next();
it.remove();
next和remove方法相互依赖,remove之前 必须调用next,如删除两个相邻元素:
it.remove();
it.remove(); //error,因为上次调用next时的元素已经被删除,不能删除两次
it.remove();
it.next();
it.remove(); //ok