实现可迭代

时间:2016-03-17 14:13:59

标签: java

我正在尝试填写练习题的空白。

除了要求使用迭代器打印序列的前20个数字的最后部分之外,我已经完成了所有部分。我不确定这样做的最佳方式是什么。

public class Duple implements Iterable{
    static Integer[] data = {1,7};

    public Iterator iterator(){
        _______return new MyIter();_____________
    }
    private class MyIter implements Iterator{
        private int curr;
        MyIter(){curr = 0;}
            public boolean _____hasNext()_______{return true;}
            public Object ___next()_________{
                Object o = data[curr];
                curr = (curr + 1) % data.length;
                return o;
           }
           public void ____remove()____ {
               throw new RuntimeException("don’t do this");
           }
       }//end MyIter
       public static void main(String[] args) {
          //Declare a new Duple and its iterator.
          ______Duple p = new Duple();__________
          ______p.iterator();___________________
         //Use the iterator to print the first twenty numbers of the
         //sequence. You may not need every line.
         ___________________________________
         ___________________________________
         ___________________________________
         ___________________________________
         ___________________________________
       }
}

1 个答案:

答案 0 :(得分:1)

您可以使用for循环:

Duple p = ...
Iterator iter = p.iterator();
for (int i = 0; i < 20 && iter.hasNext(); i++)
    System.out.println(iter.next());