この表現を持つネストされたコレクションがありCollection<Collection<T>>
ます。クラスに Iterator を実装しましたが、next() メソッドで正しい結果が得られません。各リストの最初の要素のみをフェッチしています。例List<List<String>>
と値は{"1","2"},{"3","4"},{"5","6"}
. クラスの完全なレイアウト。
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
public class NestedCollectionIterator implements Iterator<Object> {
private Collection<? extends Collection<? extends Object>> _collOfColl = null;
private Iterator<? extends Collection<? extends Object>> itCollection = null;
private Iterator<? extends Object> innerIterator = null;
Object next = null;
public NestedCollectionIterator( Collection<? extends Collection<? extends Object>> collofColl){
_collOfColl = collofColl;
itCollection = _collOfColl.iterator();
}
@Override
public boolean hasNext() {
if(itCollection.hasNext()){
innerIterator = itCollection.next().iterator();
if(innerIterator != null || innerIterator.hasNext()){
next = innerIterator.next();
return true;
}
}
return false;
}
public Object next() {
if(hasNext()){
Object obj = next;
//Need some changes here.
return obj;
}
return null;
}
@Override
public void remove() {}
}
実装をテストするクラス
class Sample{
public static void main(String[] args){
List<List<String>> Nestedlist = new ArrayList<List<String>>();
List<String> l = new ArrayList<String>();
l.add("1");
l.add("2");
Nestedlist.add(l);
l = new ArrayList<String>();
l.add("3");
l.add("4");
Nestedlist.add(l);
l = new ArrayList<String>();
l.add("5");
l.add("6");
Nestedlist.add(l);
NestedCollectionIterator cc = new NestedCollectionIterator(Nestedlist);
while(cc.hasNext()){
System.out.println(cc.next.toString());
}
}
}
結果は 1、3、5 です。最初にリスト内のすべての要素を反復処理してから、その中の次のコレクション項目に移動するにはどうすればよいですか?
ありがとう。