使用带有
Java 7的eclipse 4.2并尝试实现List接口的以下方法,我收到了警告.
public <T> T[] toArray(T[] a) { return a; }
警告说:
The type parameter T is hiding the type T
为什么?我怎么能摆脱它?
解决方法
List接口也是通用的.确保您没有在类中使用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 }
}