2010-09-26 58 views
4

我需要您查看我对单链表(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() 
    { 

    } 
} 
+2

为什么不直接使用内置的java.util.LinkedList中?想到的唯一原因是,如果这是一项家庭作业,或者您想了解链接列表和泛型如何工作。 (如果这是作业,你应该用'作业'标记) – MatrixFrog 2010-09-26 21:57:48

回答

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

您应该返回从iterator方法的Iterator<T>,你也应该扩展Iterable<T>而不是Iterable<Object>

此外,您的MyLinkedListIterator<T>应实施Iterator<T>。那么它应该工作。

1

你为什么不使用<E>

public class Node<E>{ 
E data; 
Node<E> next; 
} 

public class SinglyLinkedList<E> { 

Node<E> start; 
int size; 
....... 
} 

here关于全面执行

1

在什么样的人说,你可能不应该暴露在公开方法Node顶部 - 节点应该是实现的纯粹内部方面。

0

展开观点:MyLinkedListIterator.next()不会移动到列表中的下一个项目。

下一个方法应该是沿着这些线路的东西得到它的工作:

public T next() { 
    if(isFirstNode) { 
     isFirstNode = false; 
     return node.data; 
    } 
    node = node.next; 
    return node.data; 
} 
相关问题