gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:41:04 26 4
gpt4 key购买 nike

我正在创建一个类,双向链表,以 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.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)*);

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

最佳答案

类定义中的Integer是通用类型参数,它隐藏了Integer包装类。

因此,您在类中使用的 new Integer(0) 是将 Integer 作为类型参数,而不是 Integer 类型本身。因为,对于类型参数 T,您不能只执行 - new T();,因为该类型在该类中是通用的。编译器不知道它到底是什么类型。因此,该代码无效。

尝试将您的类(class)更改为:

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

它会起作用的。但我怀疑你真的想要这个。我想您想在泛型类中实例化类型参数。嗯,这不可能直接实现。

您在实例化该类时传递实际类型参数,如下所示:

DoublyLinkedList<Integer> dLinkedList = new DoublyLinkedList<>();

P.S:如果你能清楚地解释你的问题陈述,并在问题中加入更多背景信息,那就更好了。

关于java - 我无法在代码中实例化 Integer 类的对象 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18952865/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com