Search code examples
javacastingsuppress-warningsunchecked

Unchecked cast in Java when casting to list of superclasses


In my Java program, I need to cast an object of type List<? extends SomeBaseClass> to List<SomeBaseClass>. If I cast it directly the compiler complains (shows a warning) that there is an unchecked cast. Even though I can be sure that all the objects can be converted to their superclass, the compiler does not notice it and reports an unchecked cast. How can I get rid of the warning? Is there any other way than @SupressWarnings("unchecked")?

P.S.: The code works fine, I am just curious whether there is a better way of doing things.

Edit:

Solution: One should only do this type of cast if he is sure the he will not change the list in the future. But it is better to cast individual objects when we take them out of the list.


Solution

  • The complier complains since if you add an object of type SomeBaseClass to your List<SomeBaseClass> list, you may "violate" the content of your List<? extends SomeBaseClass> list.

    Here in an example when Number figures as your SomeBaseClass:

    List<? extends Number> doubles = new ArrayList<Double>();
    List<Number> nums = (List<Number>) doubles;
    
    nums.add(new Integer(5));    // no compiler complaints here...
    
    // doubles now contains an Integer value!
    

    If there is no way around this in your case, I believe the @SuppressWarnings("unchecked") is your best option here.