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?
Generic classes are used to provide the type safe structure -- type safe means only one type of data can be contained within Generic classes. The data type is defined at the time of an object initialization. We can have a different type of collection.
There are many advantages to using generic collections and delegates: Type safety. Generics shift the burden of type safety from you to the compiler. There is no need to write code to test for the correct data type because it is enforced at compile time.
Generics are similar to collections, but implemented using Type parameters. Generic collections accept a type parameter and accept the elements of only those type for which the generic collection is instantiated. These enforce strict type checks.
Generic collections are defined by the set of interfaces and classes. Below table contains the frequently used classes of the System.Collections.Generic namespace: Class name. Description. Dictionary<TKey,TValue>
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);
}
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With