St.Antario
St.Antario

Reputation: 27375

Why is this not cast safe?

I have the following utility class:

public class MyUtils{

    public static <T> List<? extends T> getList(Class<T> clazz){
        //returning some list
    }
}

And a class that uses the method:

public class MyClass<T>{

    public static List<MyClass<?>> values(){
        return (List<MyClass<?>>) MyUtils.getList(MyClass.class); //Warning, unchecked cast.
    }
}

It's not clear why this isn't cast safe? The result of the method cannot be assigned to a variable like this:

List<MyClass<? extends Integer>> lst = MyClass.values(); //compile-error

The only way we can assign the result of the method is this:

List<MyClass<?>> dsss = MyClass.values();

So, what kind of runtime-error may such a cast lead to?

Upvotes: 4

Views: 83

Answers (1)

JB Nizet
JB Nizet

Reputation: 691685

getList() returns a list of an unknown type. And you're casting it to a List<MyClass<?>>. How could it be safe?

Suppose the returned list is a List<MyFirstSubClassOfMyClass>. After you've casted it to List<MyClass<?>>, you'll be able to add an instance of MyClass to the list, although the list is supposed to only contain instances of MyFirstSubClassOfMyClass.

Upvotes: 4

Related Questions