java泛型,未经检查的警告

标签 java generics unchecked

这是 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 just List?

这样编译器就可以在编译时捕获上述错误,而不是运行时。这是泛型的要点。

Why in this code instead of elArray = new ListaConPI[numVertices+1] wouldnt we write elArray = new ListaConPI<Adyacente>[numVertices+1]?

因为您不能实例化泛型类型的数组(尽管您可以将此类数组声明为变量或方法参数)。参见 this earlier answer of mine to the same question .

关于java泛型,未经检查的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7009226/

相关文章:

Java 泛型 : Foo<T>, Foo、Foobar<T extends Foo<T>> 和 Foobar<T extends Foo>

.net - 在 VB.Net 中进行未经检查的整数加法的最快方法?

java - 使用 Mockito 时避免未经检查的警告

java - TinyMCE 从 Applet 内容插入图像

java - apache.commons.text 余弦距离

java - 有没有办法使用通用的 Spring Data JPA 存储库实现?

java - Collections.sort() 上未经检查的方法调用警告

java - 尝试在 spring 框架中进行构造函数注入(inject)时出错

java - Java 中的随机数真的不可预测吗?

c# - 将通用接口(interface)的实现分配给属性