2017-02-04 63 views
1

我是一個Java初學者,我必須從Iterator<Iterator<Integer>>這樣的東西中接收數值。例如,我們可能有:通過二維數組迭代,就好像它是一維數組一樣使用迭代器

{{1, 2}, {3, 4}, {5, 6}} 

next()結果應該是1。如果我們再試一次next() - 2,則 - 3,4等等。就像從1D數組中逐個獲取值,而是從2D數組中獲取值。我們應該不要複製什麼。所以,我寫了下面的一些不好的代碼:

public class IteratorNext { 

    private Iterator<Iterator<Integer>> values = null; 
    private Iterator<Integer> current; 

    public IteratorNext(Iterator<Iterator<Integer>> iterator) { 
     this.values = iterator; 
    } 

    public int next() throws NoSuchElementException { 
     current = values.next(); 
     if (!current.hasNext()) { 
      values.next(); 
     } 
     if (!values.hasNext() && !current.hasNext()) { 
      throw new NoSuchElementException("Reached end"); 
     } 
     return current.next(); 
    } 
} 

該代碼是不正確的,因爲next()結果是1,然後3,然後5因爲這裏異常的。如何解決這個問題?

+0

是否使用'Java的8'?然後有一個更簡單的方法來做到這一點。 – CKing

回答

1

,你可以採取flatMapToInt功能的優勢,你的二維數組化解成一維數組(array2d可以假定給大家做個參考,以你的二維數組):

Arrays.stream(array2d).flatMapToInt(Arrays::stream).forEach(System.out::println); 

,如果你要堅持你的解決方案,你需要修改next方法如下:

public int next() throws NoSuchElementException { 
    int result = -1; 
    //Are we already iterating one of the second dimensions? 
    if(current!=null && current.hasNext()) { 
     //get the next element from the second dimension. 
     result = current.next(); 
    } else if(values != null && values.hasNext()) { 
     //get the next second dimension 
     current = values.next(); 
     if (current.hasNext()) { 
      //get the next element from the second dimension 
      result = current.next(); 
     } 
    } else { 
     //we have iterated all the second dimensions 
     throw new NoSuchElementException("Reached end"); 
    } 

    return result; 

} 
0

每次調用next()時,都必須處理結果。

您的next()方法的第一行會跳過第一個元素,因爲您在next()方法的末尾記得current.next()。

更一般地說,這段代碼並不是處理集合的正確方法。您必須根據使用情況分析問題。

0

的問題是,每次調用next()開始使用

current = values.next(); 

因此,在每次叫你跳到下一個迭代器,而不會試圖繼續在當前迭代。

相反,你應該如果你正在使用Java的8這樣做

if(!current.hasNext()) 
    current = values.next(); 
1
public static class IteratorNext { 

    private Iterator<Iterator<Integer>> values = null; 
    private Iterator<Integer> current; 

    public IteratorNext(Iterator<Iterator<Integer>> iterator) { 
     this.values = iterator; 
    } 

    public int next() throws NoSuchElementException { 

     if (current != null && current.hasNext()) { 
      Integer val = current.next(); 
      return val; 
     } 

     if (values != null && values.hasNext()) { 
      current = values.next(); 
      if (current != null && current.hasNext()) { 
       Integer val = current.next(); 
       return val; 
      } 
     } 

     throw new NoSuchElementException("Reached end"); 

    } 
} 
+0

對第三個if條件中的'current'進行'null'檢查並不是真正必需的,因爲'current'代表了一個'Iterator',它永遠不會是'null'。 – CKing

+1

如果你解釋你的修改,那將會很好。 – andih