2014-01-24 31 views
1

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

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

回答

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); 
} 
1

It.next()返回的下一个项目。

你在你的代码做的是调用it.next()两次

0

因为旁边()上的指针每次移动,所以当你打印出来,将打印的最后一个,然后再尝试继续行

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); 
} 

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

相关问题