Search code examples
javanosuchelementexception

Getting a java.util.NoSuchElementException even though I call .next() once


Even though I have called Iterator.next() I'm still having the nosuchelementexception.

ListIterator<BankAccount_4> userDataIterator = userData.listIterator();
                        while (userData.iterator().hasNext()){
                            BankAccount_4 bankAccount4 = userDataIterator.next();
                           if (bankAccount4.getAccountNum()!=bankAccount_4.getAccountNum()) {
                               userDataIterator.add(bankAccount_4);
                               String fileName = bankAccount4.getAccountNum() + " - " + bankAccount4.getCustomerAccName() + "'s Account details";
                               dataPersistency(displayAccount(bankAccount4) + "\n\n" + computeInterest(bankAccount4), fileName);
                           }
                       }

Solution

  • Your second line ( while (userData.iterator().hasNext()){ ) appears to be retrieving a new iterator every time. The new iterator is probably not at the same place as the existing one, so you're always asking whether there's an element after the start (in a really inefficient way). I suspect what's happening is that you're iterating clear off the end of the list, because the while condition is always true.

    Why aren't you just querying the iterator you already have ( userDataIterator.hasNext() )? Even better, why not just use a Java for-each loop and skip explicitly messing with iterators at all? It's basically syntactic sugar for what you're doing, but more concisely and without the risk of screwing it up.