【问题标题】:arraylist iterator equals returns java.util.NoSuchElementExceptionarraylist 迭代器等于返回 java.util.NoSuchElementException
【发布时间】:2013-01-18 17:14:36
【问题描述】:
while(it.hasNext())
{
System.out.println("List: " +it.next().getProduct().getName() + " " + product.getName());
if (it.next().getProduct().getName().equals(product.getName()))
{
System.out.println("asd");
}
}
它返回完全相同的东西:
列表:苹果苹果
列表:橙橙
但是当我尝试比较它们时,我得到了
列表:橙橙
线程“AWT-EventQueue-0”java.util.NoSuchElementException 中的异常
问题出在 if () 行。我是否将它们与 getName() 进行比较都没关系(因为它们是相同的对象。)有什么想法吗?
【问题讨论】:
标签:
java
exception
arraylist
iterator
【解决方案1】:
您应该在每次迭代中只调用一次next() 方法。每次调用next() 方法时,它将光标移动到下一个元素。您不想这样做,以确保在每次调用 next() 之前执行 hasNext(),以避免超过最后一个元素。
应该是这样的
Product p = it.next();
//and use p onwards
【解决方案2】:
每个 next() 调用都会向前移动迭代器。您在代码中调用它两次。因此,要么在第二个 next() 前面添加 haveext(),要么删除 next() 的第二个调用
【解决方案3】:
Product temp = null; // might break your equals if written badly
while ( it.hasNext() ) {
// get next product
Product product = it.next().getProduct(); // use this when you need to refer to "next" product
if ( product.equals( temp ) ) { // compare previous product (temp) with this product
// do something
}
temp = product; // set temp equal to current product, on next iteration it is last
}