2015-01-13 53 views
0

我需要使用泛型实现自定义链表。如何让我的自定义链表使用泛型?

这里是我做了什么

public class Node { 
    Node next; 
    Object data; 

    public Node(Object data) { 
     next = null; 
     this.data = data; 
    } 

    public Object getData() { 
     return data; 
    } 

    public void setData(Object dataValue) { 
     data = dataValue; 
    } 

    public Node getNext() { 
     return next; 
    } 

    public void setNext(Node nextValue) { 
     next = nextValue; 
    } 
} 


public class LinkedList { 

    private Node head; 
    private int size; 

    public LinkedList() { 
     head = new Node(null); 
     size = 0; 
    } 

    public void add(Object data) { 
     Node node = new Node(data); 
     Node current = head; 
     while (current.getNext() != null) { 
      current = current.getNext(); 
     } 
     current.setNext(node); 
     size++; 
    } 

    public int getSize() { 
     return size; 
    } 

    public String toString() { 
     Node current = head.getNext(); 
     String elements = ""; 
     while (current != null) { 
      elements += "[" + current.getData().toString() + "]"; 
      current = current.getNext(); 
     } 
     return elements; 
    } 
} 

public class Main { 

    public static void main(String[] args) { 
     System.out.println("Hello there!"); 
     LinkedList list = new LinkedList(); 

     list.add("First node"); 
     list.add("Second node"); 
     list.add("Third node"); 
     list.add("Fourth node"); 
     list.add("Fifth node"); 

     System.out.println("Linked list contains " + list.getSize() + " nodes"); 
     System.out.println("Here they are: " + list); 
    } 
} 

我不知道,或者只是不明白,我应该使用泛型和如何?有任何想法吗?

+1

为什么不使用java LinkedList类型? –

+0

@GuillaumeS看起来像功课 –

+0

Luiggi,猜对了 – user3127896

回答

5

开始Node类;具体而言,您可以使其包含任何类型的数据。

你做,在这种方式:

  • 类级别

    public class Node<T> { } 
    
  • 介绍泛型类型参数,只要你有Object,与T更换。

    T data; 
    
  • 务必使他们使用相同的通用参数更新到内部其它Node实例的引用。现在

    Node<T> next; 
    

,您可以解决类似的方式在LinkedList类的问题。

  • 在类级

    public class LinkedList<T> { } 
    
  • 变化addObject的参数T介绍一种一般类型参数。

    public void add(T data) { } 
    
  • ,这样你不使用原始类型添​​加泛型您Node实例(S)。

    private Node<T> head; 
    
+0

很好的解释,谢谢! – user3127896

1

你应该考虑通过Generics tutorial去。具体来说,请阅读'Generic Types'部分。

基本上,您的LinkedList和Node实现需要通用,只需将它们声明为LinkedList<T>Node<T>即可。一旦你已经改变了类是通用的,可以再实例化一个参数的LinkedList,如:

LinkedList<String> stringList = new LinkedList<>(); 

的LinkedList的是现在类型安全的,并只允许字符串存储。

+0

忘记格式化代码 - 通用参数未显示。 –

+0

好的。 ***好多了。如果我在那里担心一会儿。 – Makoto

相关问题