Java中的LinkedList实现与泛型和增强

nun*_*nos 4 java generics iterator iterable data-structures

我需要您查看我的单一链接列表(SLL)的实现.实现应该使用泛型并且能够使用增强的for.

问题是,当我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 () 
    {

    }   
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*son 8

  • 你应该Iterable<T>而不是Iterable<Object>.
  • add(Node) 实际上并没有将对象添加到列表中.
  • MyLinkedListIterator<T>应该实施Iterator<T>.
  • MyLinkedListIterator.hasNext()NullPointerException如果列表为空,将抛出一个.
  • MyLinkedListIterator.next() 不会移动到列表中的下一个项目.