[英]java generics, unchecked warnings
這是 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
In detail, a heap pollution situation occurs when the List object l, whose static type is List<Number>
, is assigned to another List object, ls, that has a different static type, List<String>
// this is from oracle tutorial
我的問題是為什么 static 類型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 elArray = new ListaConPI[numVertices+1]
而不是elArray = new ListaConPI<Adyacente>[numVertices+1]
?
非常感謝 !
我的問題是為什么 static 類型是
List<Number>
而不僅僅是List
?
這樣編譯器就可以在編譯時而不是運行時捕獲像上面這樣的錯誤。 這是generics的要點。
為什么在這段代碼中我們不寫 elArray = new
elArray = new ListaConPI[numVertices+1]
而不是elArray = new ListaConPI<Adyacente>[numVertices+1]
?
因為您無法實例化泛型類型的 arrays(盡管您可以將此類 arrays 聲明為變量或方法參數)。 請參閱我對同一問題的較早回答。
List l = // something;
l 的類型是什么? 它是一個列表,即它的 static 類型,它可以是任何舊列表。 因此,如果您分配
List<String> listOfString = l;
編譯器在編譯時無法知道這是否安全。 您展示的示例表明它是不安全的,並且 ClassCastException 結果。
請閱讀有關類型擦除的信息。 現在,在刪除類型后重新考慮你的代碼(我只會做第一個例子):
List l = new ArrayList(); // Compiler remembers that it should check that only numbers can be added
List ls = l; // Compiler remembers that it should cast everything back to a String
l.add(0, new Integer(42)); // the compiler checks that the second parameter is a Number.
String s = ls.get(0); // The compiler casts the result back to a String, so you get an exception
出於同樣的原因,您不能擁有這樣的 class:
class A<T> {
public void method(T obj) { }
public void method(Object obj) { }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.