[英]How to create a Java Iterator for 2D array/list
最近有人問我一個問題,即如何為2D數組創建Java迭代器,特別是如何實現:
public class PersonIterator implements Iterator<Person>{
private List<List<Person>> list;
public PersonIterator(List<List<Person>> list){
this.list = list;
}
@Override
public boolean hasNext() {
}
@Override
public Person next() {
}
}
一維數組通過使用索引來跟蹤位置非常簡單明了,有關如何對2D列表執行此操作的任何想法。
在1D情況下,您需要保留一個索引來知道您離開的位置,對嗎? 好吧,在2D情況下,您需要兩個索引:一個索引要知道您在哪個子列表中工作,另一個索引要知道您在該子列表中的哪個元素上留下了。
像這樣嗎 (注:未經測試)
public class PersonIterator implements Iterator<Person>{
// This keeps track of the outer set of lists, the lists of lists
private Iterator<List<Person>> iterator;
// This tracks the inner set of lists, the lists of persons we're going through
private Iterator<Person> curIterator;
public PersonIterator(List<List<Person>> list){
// Set the outer one
this.iterator = list.iterator();
// And set the inner one based on whether or not we can
if (this.iterator.hasNext()) {
this.curIterator = iterator.next();
} else {
this.curIterator = null;
}
}
@Override
public boolean hasNext() {
// If the current iterator is valid then we obviously have another one
if (curIterator != null && curIterator.hasNext()) {
return true;
// Otherwise we need to safely get the iterator for the next list to iterate.
} else if (iterator.hasNext()) {
// We load a new iterator here
curIterator = iterator.next();
// and retry peeking to see if the new curIterator has any elements to iterate.
return hasNext();
// Otherwise we're out of lists.
} else {
return false;
}
}
@Override
public Person next() {
// Return the current value off the inner iterator if we can
if (curIterator != null && curIterator.hasNext()) {
return curIterator.next();
// Otherwise try to iterate along the next list and retry getting the next one.
// This won't infinitely loop at the end since next() at the end of the outer
// iterator should result in an NoSuchElementException.
} else {
curIterator = iterator.next();
return next();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.