java 同时拥有 Iterator.forEachRemaining() 和 Iterable.forEach() 有什么意义?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42465871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:40:06  来源:igfitidea点击:

what's the point of having both Iterator.forEachRemaining() and Iterable.forEach()?

javaforeachiteratoriterable

提问by mostafa.S

and both of them get a Consumer as parameter. so if Java 8, is meant to avoid confusions, like it has done in Time API, why has it added a new confusion? or am I missing some point?

并且他们都得到一个 Consumer 作为参数。所以如果 Java 8 是为了避免混淆,就像它在 Time API 中所做的那样,为什么它增加了一个新的混淆?或者我错过了什么?

回答by Sweeper

To understand why the two methods both exist, you need to first understand what are Iteratorand Iterable.

要了解为什么这两种方法都存在,您首先需要了解什么是IteratorIterable

An Iteratorbasically is something that has a "next element" and usually, an end.

一个Iterator基本的东西,有一个“未来元素”,通常,一个结束。

An Iterableis something that contains elements in a finite or infinite sequence and hence, can be iteratedover by keep getting the next element. In other words, Iterables can be iterated over by Iterators.

AnIterable是包含有限或无限序列中的元素的东西,因此可以通过不断获取下一个元素来迭代。换句话说,Iterables 可以被 s 迭代Iterator

Now that you understand this, I can talk about what's the difference between the two methods in question.

既然明白了这一点,我就可以谈谈所讨论的两种方法之间的区别。

Let's use an array list as an example. This is what is inside the array list:

我们以数组列表为例。这是数组列表中的内容:

[1, 3, 6, 8, 0]

Now if I call Iterable.forEach()and pass in System.out::print(), 13680will be printed. This is because Iterable.forEachiterates through the whole sequence of elements.

现在,如果我调用Iterable.forEach()并传入System.out::print()13680将被打印。这是因为Iterable.forEach遍历整个元素序列。

On the other hand, if I get the Iteratorof the array list and called nexttwice, before calling forEachRemainingwith System.out::print(), 680will be printed. The Iteratorhas already iterated through the first two elements, so the "remaining" ones are 6, 8 and 0.

另一方面,如果我获得Iterator数组列表的 并调用next两次,则在调用forEachRemainingwith之前System.out::print()680将打印。在Iterator已经通过前两个元素迭代,因此,“剩余”的有6,8和0。