Can anyone help me I am trying to make a class NodeIter that
Can anyone help me, I am trying to make a class NodeIter<T> that iterates over the values stored in a linked list from a Node<T> objects. The class needs to be implemented using the java.util.Iterator<T> interface. (Which is located here https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html)
I think I have implemented the constructor and the hasNext() function correctly, what I need help with is next() method which returns the next element in the iteration.
I have given the code I have so far for the NodeIter<T> class and also the Node<T> class
import java.util.*;
public class NodeIter<T>
{
public Node<T> next;
public NodeIterator(Node<T> n)
{
next = n;
}
public boolean hasNext()
{
return next != null;
}
public T next()
{
if(hasNext())
{
Node<T> curr = next;
return curr;
}
return null;
}
}
public final class Node<T>
{
public final T v;
public Node<T> next;
public Node (T val, Node<T> link)
{
v = val;
next = link;
}
}
Solution
import java.util.NoSuchElementException;
import java.util.Iterator;
public class Range implements Iterable<Integer> {
private int start, end;
public Range(int start, int end) {
this.start = start;
this.end = end;
}
public Iterator<Integer> iterator() {
return new RangeIterator();
}
// Inner class example
private class RangeIterator implements
Iterator<Integer> {
private int cursor;
public RangeIterator() {
this.cursor = Range.this.start;
}
public boolean hasNext() {
return this.cursor < Range.this.end;
}
public Integer next() {
if(this.hasNext()) {
int current = cursor;
cursor ++;
return current;
}
throw new NoSuchElementException();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
public static void main(String[] args) {
Range range = new Range(1, 10);
// Long way
Iterator<Integer> it = range.iterator();
while(it.hasNext()) {
int cur = it.next();
System.out.println(cur);
}
// Shorter, nicer way:
// Read \":\" as \"in\"
for(Integer cur : range) {
System.out.println(cur);
}
}
}

