1

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

但是我的程序返回一个错误: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);
    }
4

4 回答 4

5

你打.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);
}
于 2014-01-24T14:25:57.533 回答
2

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

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则会抛出 a。因此,调用next()两次而不在每次调用之前检查元素是否仍然可用 usinghasNext()将具有您描述的行为。

while()应该替换为:

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

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

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

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

于 2014-01-24T14:32:44.060 回答
1

It.next()返回下一项。

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

于 2014-01-24T14:26:28.480 回答
0

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

于 2014-01-24T14:27:07.530 回答