类型参数T使用Eclipse将类型T隐藏在<T> T [] toArray(T [] a)中

6 java eclipse generics warnings

使用带有Java 7的eclipse 4.2并尝试实现List接口的以下方法,我收到了警告.

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

}
Run Code Online (Sandbox Code Playgroud)

警告说:

类型参数T隐藏类型T.

截图

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

Cha*_*ion 12

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
}
Run Code Online (Sandbox Code Playgroud)

}