問題描述
我剛剛在一份舊試卷中發現了這個試題,并且正在為即將到來的考試做準備.我想不通:
I just found this exam question in an old exam paper and am readying myself for an upcoming exam. I cannot figure it out :
下面描述了一個人為的部分類,它實現了 Iterable 接口.此類的唯一目的是提供一種方法來迭代屬性 things.
The following depicts a contrived partial class which implements the Iterable interface. The only purpose of this class is to provide a method to iterate over the attribute things.
我們需要在課堂上填寫兩件事來完成它.這里是類
There are two things we need to fill in in the class to finish it. Here is the class
private class PartialIterableClass /*FILL IN */ {
private String[] things;
public PartialIterableClass( String[] things ){
this.things = things;
}
/*FILL IN 2*/
}
我猜它應該類似于:
private class PartialIterableClass implements Iterable<PrivateIterableClass> {
private String[] things;
public PartialIterableClass( String[] things ){
this.things = things;
}
public Iterator<PartialIterableClass> iterator( ){
return new Iterator<PartialIterableClass>( ) {
}
}
}
不過,我不確定如何充實這個問題的答案,有人可以幫忙嗎?
I'm not really sure how to flesh out an answer to this question though, can anybody help?
推薦答案
你的 Iterator
必須實現 Iterator
接口中的所有方法,才能封裝迭代邏輯.
Your Iterator
must implement all the methods from the Iterator
interface in order to encapsulate the iteration logic.
在您的情況下,它必須保存數組中的當前迭代索引.您可以查看 ArrayIterator
來自 commons-collections
In your case, it will have to hold the current iteration index in the array. You can look at ArrayIterator
from commons-collections
這篇關于實現 Iterable 接口的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!