Joh*_*ree 25
当你得到一个迭代器并跨过它时,那就是一个外部迭代器
for (Iterator iter = var.iterator(); iter.hasNext(); ) {
Object obj = iter.next();
// Operate on obj
}
Run Code Online (Sandbox Code Playgroud)
将函数对象传递给方法以在列表上运行时,这是一个内部迭代器
var.each( new Functor() {
public void operate(Object arg) {
arg *= 2;
}
});
Run Code Online (Sandbox Code Playgroud)
Chr*_*ton 11
我找到了这个描述:
外部与内部迭代器.
外部迭代器 - 当迭代由集合对象控制时,我们说我们有一个外部迭代器.
在像.net或java这样的语言中,创建外部迭代器非常容易.在我们的经典实现中,实现了外部迭代器.在以下示例中,使用外部迭代器:
// using iterators for a clloection of String objects:
// using in a for loop
for (Iterator it = options.iterator(); it.hasNext(); ) {
String name = (String)it.next();
System.out.println(name);
}
// using in while loop
Iterator name = options.iterator();
while (name.hasNext() ){
System.out.println(name.next() );
}
// using in a for-each loop (syntax available from java 1.5 and above)
for (Object item : options)
System.out.println(((String)item));
Run Code Online (Sandbox Code Playgroud)
内部迭代器 - 当迭代器控制它时,我们有一个内部迭代器
另一方面,实现和使用内部迭代器确实很困难.使用内部迭代器时,意味着将运行代码委托给聚合对象.例如,在提供支持的语言中很容易调用内部迭代器:
collection do: [:each | each doSomething] (Smalltalk)
Run Code Online (Sandbox Code Playgroud)
主要思想是将要执行的代码传递给集合.然后集合将在内部调用每个组件上的doSomething方法.在C++中,可以将doMethod方法作为指针发送.在C#,. NET或VB.NET中,可以将该方法作为委托发送.在java Functor中,必须使用设计模式.主要思想是仅使用一种方法(doSomething)创建基本接口.然后,该方法将在实现接口的类中实现,并且该类将被传递给集合以进行迭代.有关详细信息,请参阅Functor设计模式.
小智 8
外部迭代器示例:
int count = 0;
Iterator<SomeStaff> iterator = allTheStaffs.iterator();
while(iterator.hasNext()) {
SomeStaff staff = iterator.next();
if(staff.getSalary() > 25) {
count++;
}
}
Run Code Online (Sandbox Code Playgroud)
内部迭代器示例:
long count = allTheStaffs.stream()
.filter(staff -> staff.getSalary() > 25)
.count();
Run Code Online (Sandbox Code Playgroud)
在图像中: