gpt4 book ai didi

java - 如何正确实现java.util.Collection类?

转载 作者:行者123 更新时间:2023-11-30 02:14:16 26 4
gpt4 key购买 nike

我想编写自己的 Linked-list< T> 并实现 java.util.Collection< T>。

我的问题是警告:“类型参数 T 隐藏类型 T”。当我重写方法 public <T> T[] toArray(T[] arg0){} 时发生这种情况

这是我的代码:

public class MyLinkedList<T>  implements Serializable,Iterable<T>, Collection<T>
{
//some constructor here.

public <T> T[] toArray(T[] arg0) // I get that error here under the <T> declaration
{
return null;
}
...
// all other methods
...
}

(我知道我可以扩展 AbstractCollection 类,但这不是我想要做的)。

有人知道如何解决这个问题吗?
我是否应该将 Collection< T> 中的参数 T 更改为其他字母,如下所示: Collection< E>

最佳答案

您收到此错误是因为方法 <T> T[] toArray(T[] arg0)采用自己的通用参数,该参数独立于通用参数 T你类(class)的。

如果您需要两种类型 T (类(class))和 T (该方法)可在 toArray 内使用实现时,您需要重命名其中一种类型。例如,Java 引用实现使用 E (对于“元素”)作为集合类的泛型类型参数:

public class MyLinkedList<E>  implements Serializable, Iterable<E>, Collection<E>
{
//some constructor here.

public <T> T[] toArray(T[] arg0)
{
return null;
}
...
// all other methods
...
}

现在两个通用参数的名称不同,这解决了问题。

关于java - 如何正确实现java.util.Collection类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49084319/

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