我无法在代码(Java)中实例化Integer类的对象
我正在创建一个类,以ListNode作为内部类的双链接列表我无法在代码(Java)中实例化Integer类的对象,java,class,generics,Java,Class,Generics,我正在创建一个类,以ListNode作为内部类的双链接列表 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
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)*);
公共类双链接列表{
/**返回此列表的表示形式:其值与相邻
*以“,”,“[”开头和“]”结尾分隔的数字。
*
*例如,对于按该顺序包含6 3 8的列表,请返回“[6,3,8]”*/
公共字符串toString(){
字符串s;
ListNode i=新ListNode(null,null,*新整数(0)*);
为什么我会出现错误,无法实例化类型
Integer
?类定义中的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 ...;
}
}
公共类双链接列表{
公共字符串toString(){
ListNode i=新ListNode(null,null,新整数(0));
返回。。。;
}
}
它会工作的。但是我怀疑你真的想要这个。我猜你想在你的泛型类中实例化类型参数。好吧,这不可能直接实现
在实例化该类时传递实际类型参数,如下所示:
DoublyLinkedList<Integer> dLinkedList = new DoublyLinkedList<>();
DoublyLinkedList dLinkedList=new DoublyLinkedList();
p.S:如果你能清楚地解释你的问题陈述,并在问题中加入更多的上下文,那就更好了。向我们展示
ListNode
类的定义。问题的最可能答案:)+1。