What you need to do Fill in the implementation of the AddX class in AddX.java. W
ID: 3590425 • Letter: W
Question
What you need to do
Fill in the implementation of the AddX class in AddX.java. We've already provided the fields and the constructor to get you started. You need to fill in the hasNext() and next() methods. Keep in mind: according to the Iterator interface, hasNext() may be called 0 or more times between every call to next(). You'll see that the tests check for this property.
package iterators; import java.util.Iterator; import java.util.NoSuchElementException; public class AddX implements Iteratorf // The Iterator that this apply object will get its input from private final Iterator input; private int x; public AddX(int x, Iterator input) this. input = input ; this.x = x; @0verride public boolean hasNext)f return true; @0verride public Integer next) fExplanation / Answer
Firstly, understand what hasNext() and next() does.
hasNext() : hasNext() method returns true if iterator have more elements.
next() : next() method returns the next element and also moves cursor pointer to the next element.
Now , here you have a class AddX, which implements Iterator interface.
And AddX constructor takes Interator<Integer> object and a variable.
Now , here i am not aware of what X variable does here.
Also, AddX constructor is taking Iterator object.
In the hasNext(), we can simply, call the hasNext() on Iterator object that is passed, i,e input.hasNext();
And in next() method , we can call the hasNext() and next() on input iterator object.
here is the code:
@Override
public boolean hasNext() {
if (input.hasNext())
return true;
else
return false;
}
@Override
public Integer next() {
while(input.hasNext())
Integer obj = input.next();
return obj;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.