Iterable和Iterator
Iterator中定义的方法 | |
---|---|
default void forEachRemaining(Consumer<? super E> action) | Performs the given action for each remaining element until all elements have been processed or the action throws an exception. |
boolean hasNext() | Returns true if the iteration has more elements. |
E next() | Returns the next element in the iteration. |
default void remove() | Removes from the underlying collection the last element returned by this iterator (optional operat |
3.调用next()方法时,迭代器九月过下一个元素,并返回刚刚越过的那个元素的引用。
4.remove()方法将会删除上次调用next方法返回的元素。调用remove()方法之前必须调用next()方法,二者之间有依赖性。
Iterable接口中定义的方法 | |
---|---|
default void forEach(Consumer<? super T> action) | Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception |
Iterator iterator() | Returns an iterator over elements of type T |
default Spliterator spliterator() | Creates a Spliterator over the elements described by this Iterable |
1.iterator方法用于返回一个实现了Iterator接口的对象。可以用这个迭代器对象依次访问集合中的每一个元素。
2.Collection接口扩展了Iterable接口,因此,对于标准类库中的任何集合都可以使用for each循环,也可以通过调用iterator.forEachRemaining方法并提供一个lambda表达式。iterator.forEachRemaining(element -> do somethig with element)
.
.
.