私はこのデモを持っています。これは、再描画されたアーキテクチャを備えた特定のソリューションを必要としませんが、なぜそのように動作するのか、それを回避するために欠けているものを理解するだけです。なぜだろうと思っています:
- コンパイラは、リストのタイプではない要素をリストに挿入できます
要素をプッシュするときではなく、要素を取得しようとすると ClassCast 例外がスローされます
import Test.*; //Inner classes import java.util.List; import java.util.ArrayList; public class Test<E extends Object> { private List<E> list = new ArrayList<E>(); public Test() {} public static void main(String[] args) { Test<String> a = new Test<String>(); a.addElement(new String()); a.addElement(new Integer(0)); // No complain in comp/run-time, I dont understand why CastException is not thrown here String class1 = a.getElement(0); String class2 = a.getElement(1); //No complain in comp but ClassCastException: Integer cannot be cast to String //Integer class3 = a.getElement(1); //Compilation error } public void addElement (Object node) { list.add((E) node); } //No complain in comp/run-time public E getElement(int index) { return list.get(index); } }
What could be a solution? Notice the line addElement where I need to pass a SuperClass, instead of type E. This is needed for my architecture, this is just a simple mock demo. But anyway the casting to type E should act as desired and throw a CastExeption in runtime, should not?