Why is this not discarded?

I have the following utility class:

public class MyUtils{

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

And the 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 is not clear why it is not safe? The result of the method cannot be assigned to such a variable:

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

The only way we can assign the result of a method is as follows:

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

So, what is the runtime error such a lithiation can lead to?

+4
source share
1 answer

getList()returns a list of type unknown . And you drop it on List<MyClass<?>>. How can this be safe?

, - List<MyFirstSubClassOfMyClass>. , List<MyClass<?>>, MyClass , MyFirstSubClassOfMyClass.

+4

Source: https://habr.com/ru/post/1614025/


All Articles