floatlee 2017-11-18 03:28 采纳率: 100%
浏览 956
已采纳

关于java中Iterable和Iterator接口的问题

java中foreach为什么设计成通过Iterable访问容器,而不直接通过Iterator访问?

这样产生特定Iterable接口,满足foreach,就需要实现两层匿名内部类,Iterable和Iterator,为什么foreach不设计成通过Iterator访问容器?
不知道多设计一层Iterable是为了什么目的。请指教,谢谢。

class ReversibleArrayList<T> extends ArrayList<T>
{
    public ReversibleArrayList(Collection<T> c) { super(c); }
    public Iterable<T> reversed()
    {
        return new Iterable<T>()
                {
                    public Iterator<T> iterator()
                    {
                        return new Iterator<T>()
                                {
                                    int current = size() - 1;
                                    public boolean hasNext() { return current > -1; }
                                    public T next() { return get(current--); }
                                    public void remove() { throw new UnsupportedOperationException(); }
                                };
                    }
                };
    }
}

通过两层匿名内部类,才得到迭代器。

  • 写回答

1条回答 默认 最新

  • threenewbee 2017-11-18 03:30
    关注

    一个类可以按照不同方式迭代,拥有多个迭代器
    迭代器可以单独实现,和Iterable分开(设计模式里面叫外部迭代器)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料