第8章 その他の Java 8 機能を理解する : 問題 8 : Collections.CheckedQueue クラス
問題
CheckedQueue
クラスの利点を示すプログラムを書け。
補足
CheckedQueue
クラスは、公開されていない。
これはjava.util.Collections
のネストクラスでCollections
のcheckedQueue
メソッドが返すクラスである。
解答
CheckedQueue
クラスは、実行時に要素の型チェックを行うQueue
である。
普通にジェネリックでQueue<E>
と宣言しても、コンパイル時に型がチェックされるだけで、実行時はノーチェックである。
例えば、Queue
を引数にとる次のようなメソッドを定義する。
private static void getMoreWork(Queue queue) { queue.offer(Paths.get("alice.txt")); // 正しい型の要素を追加 queue.offer("war-and-peace.txt"); // 間違った型の要素を追加 }
このようなコードだと、コンパイラーは警告を出すが、コンパイル自体はできてしまう。
■ 通常のケース
Queue<Path> queue = new ArrayDeque<Path>(); getMoreWork(queue); Object value; while ((value = queue.poll()) != null) { System.out.println(((Path)value).isAbsolute()); // ← ここでキャストエラー }
■ CheckedQueue
を使ったケース
Queue<Path> queue = new ArrayDeque<Path>(); queue = Collections.checkedQueue(queue, Path.class); getMoreWork(queue); // ← このメソッド内でキャストエラー Object value; while ((value = queue.poll()) != null) { System.out.println(((Path)value).isAbsolute()); }