我需要您查看我对单链表(SLL)的实现。该实现应该使用泛型并能够使用增强型for。在Java中使用泛型进行LinkedList实现并对其进行了增强
的问题是,当我做for (Number n : list)
是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()
{
}
}
为什么不直接使用内置的java.util.LinkedList中?想到的唯一原因是,如果这是一项家庭作业,或者您想了解链接列表和泛型如何工作。 (如果这是作业,你应该用'作业'标记) – MatrixFrog 2010-09-26 21:57:48