作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
在 Java 7 中使用 eclipse 4.2 并尝试实现 List 接口(interface)的以下方法时,我收到了警告。
public <T> T[] toArray(T[] a) {
return a;
}
警告说:
The type parameter T is hiding the type T
为什么?我怎样才能摆脱它?
最佳答案
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/
我是一名优秀的程序员,十分优秀!