这是 oracle 页面中的部分教程:
考虑以下示例:
List l = new ArrayList<Number>();
List<String> ls = l; // unchecked warning
l.add(0, new Integer(42)); // another unchecked warning
String s = ls.get(0); // ClassCastException is thrown
具体来说,当静态类型为List<Number>
的List对象l时,会出现堆污染的情况。 , 被分配给另一个 List 对象 ls,它具有不同的静态类型 List<String>
//这是来自 oracle 教程
我的问题是为什么静态类型是 List<Number>
而不仅仅是 List
??
稍后另一个问题将来 self 的研究代码:
public class GrafoD extends Grafo {
protected int numV, numA;
protected ListaConPI<Adyacente> elArray[];
*/** Construye un Grafo con un numero de vertices dado*
* @param numVertices: numero de Vertices del Grafo
*/
@SuppressWarnings("unchecked")
public GrafoD(int numVertices){
numV = numVertices; numA=0;
elArray = new ListaConPI[numVertices+1];
for (int i=1; i<=numV; i++) elArray= new LEGListaConPI<Adyacente>();
}
为什么在此代码中而不是 elArray = new ListaConPI[numVertices+1]
我们不会写 elArray = new ListaConPI<Adyacente>[numVertices+1]
?
非常感谢!
最佳答案
my question would be why is the static type
List<Number>
and not justList
?
这样编译器就可以在编译时捕获上述错误,而不是运行时。这是泛型的要点。
Why in this code instead of
elArray = new ListaConPI[numVertices+1]
wouldnt we writeelArray = new ListaConPI<Adyacente>[numVertices+1]
?
因为您不能实例化泛型类型的数组(尽管您可以将此类数组声明为变量或方法参数)。参见 this earlier answer of mine to the same question .
关于java泛型,未经检查的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7009226/