是“无限”迭代器坏设计? [英] Is an "infinite" iterator bad design?

查看:190
本文介绍了是“无限”迭代器坏设计?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般认为不好的做法是提供 Iterator 是无限的实现;即的调用hasNext() always(*)return true?

Is it generally considered bad practice to provide Iterator implementations that are "infinite"; i.e. where calls to hasNext() always(*) return true?

Typically I'd say "yes" because the calling code could behave erratically, but in the below implementation hasNext() will return true unless the caller removes all elements from the List that the iterator was initialised with; i.e. there is a termination condition.  Do you think this is a legitimate use of Iterator?  It doesn't seem to violate the contract although I suppose one could argue it's unintuitive.

(Pedantic)EDIT

有些人评论了如何使用迭代器从无界序列(例如斐波纳契序列。然而,Java Iterator 文档声明一个迭代器是:

(Pedantic) EDIT


一个集合。

Some people have commented how an Iterator could be used to generate values from an unbounded sequence such as the Fibonacci sequence. However, the Java Iterator documentation states that an Iterator is:

现在你可以认为Fibonacci序列是一个无限集合,但在Java中,我会将集合与 java.util.Collection 接口,它提供了诸如 size()等方法,意味着集合必须是有界的。因此,是否合法使用 Iterator 作为无限序列中的值生成器?

An iterator over a collection.

推荐答案

我认为完全合法 - 迭代器只是一个stuff流。为什么流必须被绑定?

解决方案

许多其他语言(例如Scala)具有内置于其中的无界流的概念,这些可以迭代。例如,使用scalaz

I think it is entirely legitimate - an Iterator is just a stream of "stuff". Why should the stream necessarily be bounded?

Plenty of other languages (e.g. Scala) have the concept of unbounded streams built in to them and these can be iterated over. For example, using scalaz

编辑:根据最少惊讶的原则,完全在上下文。例如,我希望此方法返回什么?

In terms of the principle of least surprise, I think it depends entirely on the context. For example, what would I expect this method to return?

public Iterator<Integer> fibonacciSequence();

这篇关于是“无限”迭代器坏设计?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆