Hi. I need you to review my implementation of a Singly Linked List (SLL) please. The implementation should use generics and be able to use the enhanced for.
The problem is that, when I do for (Number n : list)
being list
a MyLinkedList<Integer>
or MyLinkedList<Double>
, I get the error: "Type mismatch: cannot convert from element type Object to Number".
This is what I have. The parts I am not very certain about are the generics and the iterators.
Thanks in advance.
import java.util.Iterator;
public class MyLinkedList<T> implements Iterable<Object>
{
private Node head;
public MyLinkedList ()
{
head = null;
}
public void add (Node n)
{
if (head == null)
{
head = n;
}
else
{
Node node = head;
while (node.next != null)
{
node = node.next;
}
node = n;
}
}
public Iterator iterator()
{
return new MyLinkedListIterator (head);
}
public int size ()
{
int ret = 0;
MyLinkedListIterator it = new MyLinkedListIterator (head);
while (it.hasNext ())
{
it.next();
ret++;
}
return ret;
}
public Node getHead ()
{
return head;
}
}
class MyLinkedListIterator<T> implements Iterator
{
private Node node;
public MyLinkedListIterator (Node h)
{
node = h;
}
public MyLinkedListIterator (MyLinkedList<T> l)
{
this(l.getHead ());
}
public boolean hasNext ()
{
if (node.next == null)
{
return false;
}
else
{
return true;
}
}
public Object next ()
{
return node.next;
}
public void remove ()
{
}
}