Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare the Iterator interface method.
LLD
interface Iterator {
boolean [1]();
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Choosing next instead of hasNext
Using remove which is optional
✗ Incorrect
The hasNext method checks if there are more elements to iterate over.
2fill in blank
mediumComplete the code to return the next element in the iterator.
LLD
public Object [1]() { if (!hasNext()) { throw new NoSuchElementException(); } return collection.get(currentIndex++); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using hasNext instead of next
Trying to remove element here
✗ Incorrect
The next method returns the next element and advances the iterator.
3fill in blank
hardFix the error in the iterator implementation to correctly check for more elements.
LLD
public boolean hasNext() {
return currentIndex [1] collection.size();
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using >= or > which causes errors
Using <= which is off by one
✗ Incorrect
The hasNext method should return true if currentIndex is less than collection size.
4fill in blank
hardFill both blanks to implement a simple iterator for an array.
LLD
class ArrayIterator implements Iterator { private Object[] items; private int [1] = 0; public ArrayIterator(Object[] items) { this.items = items; } public boolean hasNext() { return [2] < items.length; } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently
Not initializing the index variable
✗ Incorrect
The variable currentIndex tracks the current position in the array for iteration.
5fill in blank
hardFill all three blanks to complete the iterator's next method.
LLD
public Object [1]() { if (!hasNext()) { throw new NoSuchElementException(); } return items[[2]++]; } public void [3]() { [2] = 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Confusing method names
Not incrementing index properly
Missing reset method
✗ Incorrect
The next method returns the current item and increments the index. The reset method sets the index back to zero.
