Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the risks of explicitly casting from a list of type List<? extends MyObject> to a list of type List<MyObject> in Java?

Tags:

java

generics

I think the title should explain it all but just in case...

I want to know what risks and potential issues relating to casting can arise from the following snippet of Java code:

List<? extends MyObject> wildcardList = someAPI.getList();
List<MyObject> typedList = (List<MyObject>) wildcardList;

My thoughts are that all objects in the wildcardList should be an instance of MyObject (exact type or subclass) and so whenever objects are retrieved from typedList then there should never be a ClassCastException. Is this correct? If so why does the compiler generate a warning?

like image 907
steinybot Avatar asked Aug 04 '10 07:08

steinybot


2 Answers

There should be no problem as long as just you retrieve objects from the list. But it could result in runtime exception if you invoke some other methods on it like the following code demonstrate:

    List<Integer> intList = new ArrayList<Integer>();
    intList.add(2);

    List<? extends Number> numList = intList;
    List<Number> strictNumList = (List<Number>) numList;
    strictNumList.add(3.5f);

    int num = intList.get(1); //java.lang.ClassCastException: java.lang.Float cannot be cast to java.lang.Integer
like image 185
Marimuthu Madasamy Avatar answered Sep 25 '22 07:09

Marimuthu Madasamy


You are correct about retrieving objects from typedList, this should work.

The problem is when you later add more objects to typedList. If, for instance, MyObject has two subclasses A and B, and wildcardList was of type A, then you can't add a B to it. But since typedList is of the parent type MyObject, this error will only be caught at runtime.

like image 34
Thomas Kappler Avatar answered Sep 24 '22 07:09

Thomas Kappler