Java入门Iterable与Iterator接口

xiaoxiao2021-02-28  54

Interface Iterable<T>

根据Java API上写:

Implementing this interface allows an object to be the target of the “for-each loop” statement.

也就是说,实现t该接口可以让类实现for循环 阅读Iterable源码,该接口有3个方法

Modifier,Type and MethodDescriptionpublic interface Iterable<T>default void forEach(Consumer 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.

可以知道,实现该接口,我们只需要实现Iterator iterator() 由API:

Iterator iterator() Returns an iterator over elements of type T. Returns: an Iterator.

我们只需要返回一个Iterator对象就可以了

Interface Iterator

Java API中说到:

An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from enumerations in two ways: Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. Method names have been improved.

其实就是一个迭代器啦…

Modifier,Type and MethodDescriptionpublic interface Iterator<E>default void forEachRemaining(Consumer 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 operation).

可以知道,实现该接口,只要实现next()与hasNext(),当有remove()需求时,也要实现该方法.

下面是具体实现

1.类名中加上implements Iterable

public class ClassName<E> implements Iterable<E>

2.实现Iterator iterator(),返回Iterator对象

public Iterator<E> iterator() { return new MyIterator<E>(); }

3.实现内部类MyIterator

private class MyIterator<E> implements Iterator<E> { public boolean hasNext() { //return true if the iteration has more elements } public E next() { if (!hasNext()) throw NoSuchElementException(); // returns the next element in the iteration } public void remove() { throw new UnsupportedOperationException(); } }
转载请注明原文地址: https://www.6miu.com/read-2625790.html

最新回复(0)