I want to implement the Iterable interface in my own linked list for a foreach method with Consumer, but I can't figure out how to make the next() method return a Node instead of the generic type. I know usually you would want iterator to be of the type of the data stored inside the Node, but I want it to be the Node itself for more flexibility. I am fairly new to generics and Java in general.
This is the relevant part of my class. Furthermore, there are some add and remove methods that are not really of interest here.
import java.util.Iterator;
class OwnList<Type> implements Iterable<T>{
class Node{
Type data;
Node next;
public Node(Type data, Node next){
this.data = data;
this.next = next;
}
}
Node head;
@Override
public <T> Iterator<T> iterator(){
Iterator<T> iterator = new Iterator<T>(){
private Node index = head;
@Override
public boolean hasNext(){
return index.next == null ? false : true;
}
@Override
public T next(){
return index = index.next;
}
@Override
public void remove(){
}
};
return iterator;
}