問題描述
如果我有一個包含 [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 的一個實現(xiàn).util.Iterator
接口.如果您正在使用來自 java.util
的現(xiàn)有可迭代對象(例如,LinkedList
),則需要對其進行子類化并覆蓋其 iterator
函數(shù),以便您返回自己的,或提供一種將標準迭代器包裝在您的特殊 Iterator
實例中的方法(其優(yōu)點是使用更廣泛),等等.
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 編寫自己的迭代器嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!