我在使用自定义迭代器时遇到了麻烦...似乎next()方法无法正常工作。

我认为我的构造函数无法正常工作...并且收到此错误消息:java.lang.ArithmeticException:/减零

import java.util.Iterator;

public class RandomBag <Item> implements Iterable<Item>
{
  private Node first;
  private int N;
  private int k=0;

  private class Node
  {
    Item item;
    Node next;
  }

  public void add(Item item)
  {
    Node oldfirst = first;
    first = new Node();
    first.item = item;
    first.next = oldfirst;
    N++;
  }

  public boolean isEmpty()
  {
    return first == null;
  }

  public int size()
  {
    return N;
  }

  public Iterator<Item> iterator()
  {
    return new RandomIterator();
  }

  private class RandomIterator implements Iterator<Item>
  {
    Item[] a = (Item[]) new Object [N];

    public RandomIterator()
    {
      int counter = 0;

      //put items in the array
      for (Node x=first; x!=null; x=x.next)
      {
        a[counter] = x.item;
        counter++;
      }

      //randomize the items in the array
      for (int i=0; i<size(); i++)
      {
        int randomIndex = StdRandom.uniform(i, size());
        Item item = a[randomIndex];
        a[randomIndex] = a[i];
        a[i] = item;
      }
    }

    public void remove() {}

    public boolean hasNext()
    {
      return k!=N;
    }

    public Item next()
    {
      Item item = a[k % a.length];
      k++;
      return item;
    }
  }
  public static void main(String[] args)
  {
    RandomBag<Double> numbers = new RandomBag<Double>();
    Iterator iter = numbers.iterator();

    numbers.add(1.0);
    numbers.add(4.0);
    numbers.add(3.0);
    numbers.add(5.0);

    StdOut.println(iter.next());
    StdOut.println(iter.next());
    StdOut.println(iter.next());
    StdOut.println(iter.next());
  }
}

最佳答案

问题在于此方法:

public Item next()
{
  Item item = a[k % a.length]; // If a.length is zero... BOOM
  k++;
  return item;
}

09-08 03:47