Java入门Iterable与Iterator接口

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 MethodDescription
public 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 MethodDescription
public 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();  }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值