我们可以用Java编写自己的迭代器吗? [英] Can we write our own iterator in Java?
问题描述
如果我有一个包含 [alice,bob,abigail,charlie]
的列表,我想编写一个迭代器,以便迭代以'a'开头的元素,我可以自己写吗?我怎样才能做到这一点 ?
If I have a list containing [alice, bob, abigail, charlie]
and I want to write an iterator such that it iterates over elements that begin with 'a', can I write my own ? How can I do that ?
推荐答案
当然。迭代器只是 java.util.Iterator
界面。如果您从 java.util
中使用现有的可迭代对象(例如, LinkedList
),则需要要么继承它并覆盖它的 iterator
函数,以便你自己返回,或者提供一种在特殊的迭代器中包装标准迭代器的方法
实例(具有更广泛使用的优点)等等。
Sure. An iterator is just an implementation of the java.util.Iterator
interface. If you're using an existing iterable object (say, a LinkedList
) from java.util
, you'll need to either subclass it and override its iterator
function so that you return your own, or provide a means of wrapping a standard iterator in your special Iterator
instance (which has the advantage of being more broadly used), etc.
这篇关于我们可以用Java编写自己的迭代器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!