集合

结构

Java类库中,集合类的基本接口是Collection接口

这个接口有两个基本方法

public interface Collection<E> extends Iterable<E> {
	boolean add(E e);
    Iterator<T> iterator();
    ...
}

add方法用于向集合添加元素,成功返回true,失败返回false

iterator返回一个实现了Iterator接口的对象。使用迭代器依次访问集合中的元素

public interface Iterator<E> {
	boolean hasNext();
    E next();
    default void remove() {};
}

通过调用Iteratornext方法,可以依次访问集合中的元素,如何到了了集合的末尾,

next方法将抛出一个NoSuchElementException.因此,调用next之前要调用hasNext方法检测。

例如遍历一个Collection

        Collection<String> c = Arrays.asList(new String[]{"aaa", "bbb", "ccc"});
        Iterator i = c.iterator();
        while (i.hasNext()){
            System.out.println(i.next());
        }

也可用使用for each循环表示同样的操作

       for (String s : c) {
            System.out.println(s);
        }

编译器会将for each翻译成带迭代器的循环。

Iterator中的remove方法会删除上次调用next方法返回的元素。

remove是依赖于next

Last Updated:
Contributors: himcs