这是 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对象l(其静态类型为List<Number>
,被分配给另一个具有不同静态类型的 List 对象 ls,List<String>
// 这是来自 oracle 教程
我的问题是为什么是静态类型List<Number>
不仅仅是List
??
后来另一个问题来自我的研究代码:
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]
?
多谢 !
我的问题是为什么是静态类型List<Number>
不仅仅是List
?
这样编译器就可以在编译时而不是运行时捕获上述错误。这是泛型的要点。
为什么在这段代码中而不是elArray = new ListaConPI[numVertices+1]
我们不应该写吗elArray = new ListaConPI<Adyacente>[numVertices+1]
?
因为您无法实例化泛型类型的数组(尽管您可以将此类数组声明为变量或方法参数)。看我之前对同一问题的回答 https://stackoverflow.com/questions/3853411/array-type-in-generics/3853444#3853444.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)