Java-generics-no-array

提供:Dev Guides
移動先:案内検索

Javaジェネリック-配列なし

パラメーター化された型の配列は許可されていません。

//Cannot create a generic array of Box<Integer>
Box<Integer>[] arrayOfLists = new Box<Integer>[2];

コンパイラは型消去を使用するため、型パラメーターはObjectに置き換えられ、ユーザーは配列に任意の型のオブジェクトを追加できます。 また、実行時に、コードはArrayStoreExceptionをスローできません。

//compiler error, but if it is allowed
Object[] stringBoxes = new Box<String>[];

//OK
stringBoxes[0] = new Box<String>();

//An ArrayStoreException should be thrown,
//but the runtime can't detect it.
stringBoxes[1] = new Box<Integer>();