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
what's the point of having both Iterator.forEachRemaining() and Iterable.forEach()?
提问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 Iterator
and Iterable
.
要了解为什么这两种方法都存在,您首先需要了解什么是Iterator
和Iterable
。
An Iterator
basically is something that has a "next element" and usually, an end.
一个Iterator
基本的东西,有一个“未来元素”,通常,一个结束。
An Iterable
is something that contains elements in a finite or infinite sequence and hence, can be iteratedover by keep getting the next element. In other words, Iterable
s can be iterated over by Iterator
s.
AnIterable
是包含有限或无限序列中的元素的东西,因此可以通过不断获取下一个元素来迭代。换句话说,Iterable
s 可以被 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()
, 13680
will be printed. This is because Iterable.forEach
iterates through the whole sequence of elements.
现在,如果我调用Iterable.forEach()
并传入System.out::print()
,13680
将被打印。这是因为Iterable.forEach
遍历整个元素序列。
On the other hand, if I get the Iterator
of the array list and called next
twice, before calling forEachRemaining
with System.out::print()
, 680
will be printed. The Iterator
has already iterated through the first two elements, so the "remaining" ones are 6, 8 and 0.
另一方面,如果我获得Iterator
数组列表的 并调用next
两次,则在调用forEachRemaining
with之前System.out::print()
,680
将打印。在Iterator
已经通过前两个元素迭代,因此,“剩余”的有6,8和0。