我无法在我的代码中实例化类Integer的对象(Java)

Ha *_*Kim 2 java generics class

我正在使用ListNode作为内部类创建一个类,Doubly Linked List.

public class DoublyLinkedList<Integer> {

    /** Return a representation of this list: its values, with adjacent
     * ones separated by ", ", "[" at the beginning, and "]" at the end. <br>
     * 
     * E.g. for the list containing 6 3 8 in that order, return "[6, 3, 8]". */
    public String toString() {
        String s;

        ListNode i = new ListNode(null, null, *new Integer(0)*);
Run Code Online (Sandbox Code Playgroud)

为什么我得到错误,无法实例化类型Integer

Roh*_*ain 9

Integer类定义中是隐藏了泛型类型参数Integer的包装类.

因此,new Integer(0)您在类中使用的是Integer作为类型参数,而不是Integer类型本身.因为,对于类型参数T,您不能只做 - new T();,因为该类型在该类中是通用的.编译器不知道它究竟是什么类型.所以,代码无效.

尝试将您的课程更改为:

public class DoublyLinkedList<T> {
    public String toString() {
        ListNode i = new ListNode(null, null, new Integer(0));
        return ...;
    }
}
Run Code Online (Sandbox Code Playgroud)

它会工作.但我怀疑你真的想要这个.我想你想在泛型类中实例化type参数.嗯,这不可能直接.

您在实例化该类时传递实际的类型参数:

DoublyLinkedList<Integer> dLinkedList = new DoublyLinkedList<>();
Run Code Online (Sandbox Code Playgroud)

PS:如果你清楚地解释你的问题陈述并在问题中加入更多的背景会更好.