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.
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.
What you're trying to do is unsafe. Consider this simple example:
import java.util.*;
class SomeBaseClass
{
}
class SomeSubClass extends SomeBaseClass
{
public static void main(String[] a)
{
List<SomeSubClass> orig = new ArrayList<SomeSubClass>();
// Compiles with no warnings. This is the purpose of the ? extends syntax
List<? extends SomeBaseClass> l1 = orig;
// This is what you're trying to do
List<SomeBaseClass> l2 = (List<SomeBaseClass>) l1;
// Then, we add a SomeBaseClass to the new list
l2.add(new SomeBaseClass());
// ClassCastException, since this casts a SomeBaseClass to a SomeSubClass
SomeSubClass first = orig.get(0);
}
}
You're downcasting, which is a bad practice. Try to refactor your code to avoid this casting. And of course you should not suppress warnings in this case.
精彩评论