Java-generics-no-array

提供:Dev Guides
2020年6月23日 (火) 01:24時点におけるMaintenance script (トーク | 投稿記録)による版 (Imported from text file)
(差分) ← 古い版 | 最新版 (差分) | 新しい版 → (差分)
移動先:案内検索

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>();