本文介绍了类型参数T在< T>中隐藏类型T, T [] toArray(T [] a)使用Eclipse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用eclipse 4.2与Java 7并试图实现下面的List接口的方法,我得到了一个警告。
public < T> T [] toArray(T [] a){
return a;
$ / code $ / pre
$ b $ p 警告说:
为什么?我怎样才能摆脱它?
解决方案 List接口也是通用的。确保你不在类中使用T作为泛型类型。请注意,在,它们使用E作为类泛型参数,T使用toArray()泛型参数。这避免了重叠。
public class MyList< T>实现List< T> {
// V1(编译器警告)
public< T> T [] toArray(T [] array){
//在此方法中,T引用通用方法
//的泛型参数,而不是类的泛型参数。因此我们收到警告。
T变量= null; //引用数组的元素类型,它可能不是MyList的元素类型
}
// V2(无警告)
public< T2> T2 [] toArray(T2 [] array){
T variable = null; //引用MyList的元素类型
T2 variable2 = null; //引用数组元素类型
}
}
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 :
Why ? How can i get rid of it ?
解决方案 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
}
}
这篇关于类型参数T在< T>中隐藏类型T, T [] toArray(T [] a)使用Eclipse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!