TheAlgorithms/Java · error · NoSuchElementException
No more elements in the bag.
Error message
No more elements in the bag.
What it means
Thrown by Bag's iterator next() when hasNext() is false — i.e., the iterator has been fully consumed and there are no more elements. This is the standard contract violation for java.util.Iterator: calling next() after exhaustion.
Source
Thrown at src/main/java/com/thealgorithms/datastructures/bags/Bag.java:131
* Checks if there are more elements to iterate over.
*
* @return {@code true} if there are more elements; {@code false} otherwise
*/
@Override
public boolean hasNext() {
return currentElement != null;
}
/**
* Returns the next element in the iteration.
*
* @return the next element in the bag
* @throws NoSuchElementException if there are no more elements to return
*/
@Override
public E next() {
if (!hasNext()) {
throw new NoSuchElementException("No more elements in the bag.");
}
E element = currentElement.content;
currentElement = currentElement.nextElement;
return element;
}
}
}
View on GitHub (pinned to fdfb9a395b)
Solutions
- Always check hasNext() before next() in explicit iterator loops.
- Prefer the enhanced for-each loop which handles the check automatically.
- For empty bags, short-circuit before iterating.
Example fix
// before
Iterator<E> it = bag.iterator();
while (true) { E e = it.next(); /* process */ }
// after
for (E e : bag) { /* process */ }
// or explicitly:
Iterator<E> it = bag.iterator();
while (it.hasNext()) { E e = it.next(); /* process */ } Defensive patterns
Strategy: validation
Validate before calling
// Always check hasNext before next
Iterator<E> it = bag.iterator();
while (it.hasNext()) {
E e = it.next();
// process e
} Try / catch
Iterator<E> it = bag.iterator();
try {
while (true) {
E e = it.next();
// process
}
} catch (NoSuchElementException e) {
// iteration complete
} Prevention
- Prefer enhanced for-each loops over manual iterator.next() calls.
- Always guard next() with hasNext().
- Never reuse an exhausted iterator; obtain a fresh one from bag.iterator().
When it happens
Trigger: Calling iterator.next() without guarding with hasNext(); using a raw while(true) loop that doesn't check hasNext(); calling next() on an iterator obtained from an empty bag.
Common situations: Manual iteration loops that forget the hasNext check; for-each loops are safe but explicit iterator.next() calls in while loops are error-prone; reusing an exhausted iterator.
Related errors
- No converter for: {}
- Number of hash functions and bit array size must be greater
- Buffer size must be positive
- Null items are not allowed
- Cannot pop from an empty stack.
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/4b9553f558a2510a.
Report an issue: GitHub.