【问题标题】:NoSuchElementException in method next() Java方法 next() Java 中的 NoSuchElementException
【发布时间】:2014-01-24 14:24:44
【问题描述】:

方法removeDuplicate(ArrayList<Card> l)的目的是根据类Card中的属性card_value删除重复的对象,然后将它们添加到ArrayList并返回arr。

但我的程序返回错误:NoSuchElementException 在该行

dum.add((Card) it.next());

我不知道这里发生了什么,因为我打印出 next() 方法返回的对象,它打印出来很完美。

请告诉我为什么我在下面的实现中出错:

private ArrayList<Card> removeDuplicate(ArrayList<Card> l){
    int end = l.size();
    Set<Card> set = new HashSet<>();

    for(int i = 0; i < end; i++){
        set.add(l.get(i));
    }
    ArrayList<Card> dummy = new ArrayList<>();
    Iterator it = set.iterator();
    while(it.hasNext()){
        System.out.println(it.next());
        dummy.add((Card) it.next());
    }

    return dummy;
}

这些是覆盖方法:

@Override
    public int hashCode() {
        int hash = 5;
        hash = 97 * hash + this.card_value;
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this){
            return true;
        }
        if (!(obj instanceof Card)){
            return false;
        }
        Card other = (Card) obj;
        return (this.card_value == other.card_value);
    }

【问题讨论】:

    标签: java nosuchelementexception


    【解决方案1】:

    您呼叫.next() 两次。 next() 获取迭代器中的下一个元素,但您只在第一个元素之前检查 hasNext()

    改变

    while(it.hasNext()){
        System.out.println(it.next());
        dummy.add((Card) it.next());
    }
    

    while(it.hasNext()){
        Card nextCard = (Card) it.next();
        System.out.println(nextCard);
        dummy.add(nextCard);
    }
    

    【讨论】:

      【解决方案2】:

      Here你可以从java Iterator看到next()方法的源代码。它看起来像这样:

      public E next() {
          checkForComodification();
          try {
              int i = cursor;
              E next = get(i);
              lastRet = i;
              cursor = i + 1;
              return next;
          } catch (IndexOutOfBoundsException e) {
              checkForComodification();
              throw new NoSuchElementException();
          }
      }
      

      如您所见,如果您不在数组中,则会抛出 NoSuchElementException。因此调用next() 两次而不在每次调用之前检查元素是否仍然可用hasNext() 将具有您描述的行为。

      您的while() 应替换为:

      while(it.hasNext()) {
          dummy.add((Card) it.next());
      }
      

      但是,如果您真的想要打印出来的内容,只需将其更改为:

      while (it.hasNext()) {
          Card card = (Card)it.next();
          System.out.println(card);
          dummy.add(card);
      }
      

      当您需要在方法或循环中多次使用对象时,如果调用的方法可能很昂贵,则第二种方法是更好的方法。

      【讨论】:

        【解决方案3】:

        It.next() 返回下一项。

        您在代码中所做的是调用 it.next() 两次

        【讨论】:

          【解决方案4】:

          因为next()每次都在指针上移动,所以当你打印出来的时候,它会打印最后一个,然后尝试再次移动到后面的那一行

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-06-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多