The type parameter T is hiding the type T in <T> T[] toArray(T[] a) using Eclipse

与世无争的帅哥 提交于 2019-12-23 09:16:13

问题


Using eclipse 4.2 with Java 7 and trying to implement the following method of the List interface i got a warning.

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

}

The warning says :

The type parameter T is hiding the type T

Why ? How can i get rid of it ?


回答1:


The List interface is also generic. Make sure that you are not also using T for the generic type in your class. Note that in http://docs.oracle.com/javase/6/docs/api/java/util/List.html, they use "E" for the class generic parameter and "T" for the toArray() generic parameter. This prevents the overlap.

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
}

}




回答2:


Another option is that you have an import of a class called "T" and that's why you are getting the warning. I have just solved my problem after finding out that i had an useless import to:

org.apache.poi.ss.formula.functions.T

tl;dr: Check your imports!



来源:https://stackoverflow.com/questions/12548205/the-type-parameter-t-is-hiding-the-type-t-in-t-t-toarrayt-a-using-eclips

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!