gpt4 book ai didi

java - 类型参数 T 使用 Eclipse 在 T[] toArray(T[] a) 中隐藏类型 T

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:51:10 29 4
gpt4 key购买 nike

在 Java 7 中使用 eclipse 4.2 并尝试实现 List 接口(interface)的以下方法时,我收到了警告。

public <T> T[] toArray(T[] a) {
return a;

}

警告说:

The type parameter T is hiding the type T

screenshot

为什么?我怎样才能摆脱它?

最佳答案

List 接口(interface)也是通用的。确保您没有将 T 也用于类中的泛型类型。请注意,在 http://docs.oracle.com/javase/6/docs/api/java/util/List.html ,他们使用“E”作为类通用参数,使用“T”作为 toArray() 通用参数。这样可以防止重叠。

public class MyList<T> implements List<T> {

// V1 (compiler warning)
public <T> T[] toArray(T[] array) {
// in this method T refers to the generic parameter of the generic method
// rather than to the generic parameter of the class. Thus we get a warning.
T variable = null; // refers to the element type of the array, which may not be the element type of MyList
}

// V2 (no warning)
public <T2> T2[] toArray(T2[] array) {
T variable = null; // refers to the element type of MyList
T2 variable2 = null; // refers to the element type of the array
}

关于java - 类型参数 T 使用 Eclipse 在 <T> T[] toArray(T[] a) 中隐藏类型 T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12548205/

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