如何使用Anytype创建有效的通用链表?

问题描述

你好,我已经创建了一个名为GenLinkedList的泛型类(它是单链接的List),但是我对理解泛型还很陌生,因此我的程序无法正确实现。

我的节点类如下:

public class Node<AnyType> {
    public AnyType value;
    public Node<AnyType> next;
    
    public Node(AnyType value,Node<AnyType> next) {
        this.value = value;
        this.next = next;
    }
    
    public Node(AnyType value) {
        this.value = value;
        this.next = null;
    }
}

我的GenLinkedList类如下:

public class GenLinkedList<AnyType> {
    private Node<AnyType> head;
    private Node<AnyType> tail;
    int size = 0;
    
    public void addFront(AnyType value) {
        if(head == null) {
            head = new Node(value);
            tail = head;
        }
        else
        {
            head = new Node(value,head);
        }
        size++;
    }
}

我的主像:

public class Main {

    public static void main(String[] args) {
         GenLinkedList list = new GenLinkedList();      // try <int> didnt work! What am I do wrong?
         
         for(int i = 0; i < 10; i++) {
             list.addFront(i);
         }
         
         System.out.println(list);
         
    }

}

解决方法

int是原始类型,您需要包装类型Integer。喜欢,

GenLinkedList<Integer> list = new GenLinkedList<>();