Reputation: 861
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?
Upvotes: 8
Views: 117
Reputation: 12755
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);
}
Upvotes: 14
Reputation: 38225
I don't think so. If that static add()
method is a fact of life (something you don't control), there's not much you can do, because Java generics are implemented so that they are compatible with Java < 5.0.
However, if you are able to change the signature of the add()
method, you can simply enforce the type check so you get compiler errors for the code in your main()
method:
public static <T> void add(List<? super T> list, T object) {
list.add(object)
}
Upvotes: 3