我需要您查看我对单链表 (SLL) 的实现。实现应该使用泛型并且能够使用增强的for。
问题是,当我for (Number n : list)
成为or时,我收到错误:“类型不匹配:无法从元素类型对象转换为数字”。list
MyLinkedList<Integer>
MyLinkedList<Double>
这就是我所拥有的。我不太确定的部分是泛型和迭代器。
提前致谢。
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 ()
{
}
}