我有點困惑:我想ArrayList的-S的數組,但我看不出有什麼方法來指定的ArrayList項目類型:如何爲新的ArrayList指定項目類型<V> [N]?
class Test<V> {
final static int N = 512;
ArrayList<V> list1 = new ArrayList<>(); // ok
ArrayList<V> list2 = new ArrayList<V>(); // ok
ArrayList<V>[] lists1 = new ArrayList[N]; // <== warning:
// Type safety: The expression of type ArrayList[] needs
// unchecked conversion to conform to ArrayList<V>[]
// Note that this line works because it's only a warning.
ArrayList<V>[] lists2 = new ArrayList<V>[N]; // <== error:
// Cannot create a generic array of ArrayList<V>
ArrayList<V>[] lists3 = new ArrayList<>[N]; // <== error:
// Incorrect number of arguments for type ArrayList<E>;
// it cannot be parameterized with arguments <>
ArrayList<V>[] lists4 = (ArrayList<V>[])new ArrayList[N]; // <== warning:
//Type safety: Unchecked cast from ArrayList[] to ArrayList<V>[]
}
我看到有
ArrayList<V>[] lists1 = new ArrayList[N];
的問題是,物品的類型未指定,但我該如何指定它?
編輯:答案是參數化類型的they disallowed生陣列。他們可能希望程序員明確地對類型安全負責。
void f() {
lists1[0] = new ArrayList<V>(); // ok
//lists1[1] = new ArrayList<String>(); // <== error:
// Type mismatch: cannot convert from ArrayList<String> to ArrayList<V>
Object[] x = lists1;
x[0] = new ArrayList<Integer>(); // ok
}
他們可能會認爲,在一些勉強相關的地方警告總比沒有警告要好:或者是因爲Test.f()編譯沒有任何警告,也許他們感到不安。
http://stackoverflow.com/questions/8559092/create-an-array-of-arraylists – Jerry06
http://stackoverflow.com/questions/2927391/whats-the-reason-i-cant-create-generic -array-types-in-java – nullpointer
http://stackoverflow.com/questions/1817524/generic-arrays-in-java –