Java中的外部和内部迭代器是什么?
发布于 2008-10-22 06:32:25
外部迭代器
当您获得一个迭代器并遍历它时,这就是一个外部迭代器
for (Iterator iter = var.iterator(); iter.hasNext(); ) {
Object obj = iter.next();
// Operate on obj
}
内部迭代器
将函数对象传递给方法以遍历列表时,这是一个内部迭代器
var.each( new Functor() {
public void operate(Object arg) {
arg *= 2;
}
});
发布于 2008-10-22 06:27:22
我找到了这个description
外部迭代器与内部迭代器。
外部迭代器-当迭代由集合对象控制时,我们说我们有一个外部迭代器。
在像.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));
内部迭代器-当迭代器控制它时,我们就有了一个内部迭代器
另一方面,实现和使用内部迭代器是非常困难的。当使用内部迭代器时,这意味着正在运行的代码被委托给聚合对象。例如,在支持这一点的语言中,很容易调用内部迭代器:
collection do: [:each | each doSomething] (Smalltalk)
其主要思想是将要执行的代码传递给集合。然后,集合将在内部调用每个组件上的doSomething方法。在C++中,可以将doMethod方法作为指针发送。在C#、.NET或VB.NET中,可以将方法作为委托发送。在java中,必须使用Functor
设计模式。主要思想是创建一个只有一个方法(doSomething)的基接口。然后,该方法将在实现该接口的类中实现,并将该类传递给集合进行迭代。有关更多详细信息,请参阅Functor
设计模式。
发布于 2018-10-25 19:17:13
外部迭代器示例:
int count = 0;
Iterator<SomeStaff> iterator = allTheStaffs.iterator();
while(iterator.hasNext()) {
SomeStaff staff = iterator.next();
if(staff.getSalary() > 25) {
count++;
}
}
内部迭代器示例:
long count = allTheStaffs.stream()
.filter(staff -> staff.getSalary() > 25)
.count();
在图像中:
https://stackoverflow.com/questions/224648
复制相似问题