2017-02-04 65 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