I use generics in Java but it isn't so good as I thought
public static void add(List l, Object o) {
l.add(o);
}
public static void main(String[] args) throws Exception {
List<Integer> list = new ArrayList<Integer>();
add(list, "1.23");
add(list, 1.23);
System.out.println(list);
}
All this compiles and works. When I get a value from list
an exception is thrown.
Can it be safer in Java 6?
I suggest using the standard Collections
:
List<Integer> checked = Collections.checkedList(list, Integer.class);
then just work on checked
. A ClassCastException
will be thrown during the insertion of any non-compliant instance - sooner (thus better) than before (i.e. during retrieval).
N.B. check your compiler messages, I'd bet you have some warnings printed in there mentioning unsafe/unchecked code.. Your problem is exactly what the compiler is trying to tell you. If you control the signature of add
, make it generic - it will give you compile-time safety.
public static <T> void add(List<T> list, T t) {
list.add(t);
}