Type erasure and solutions

Type erasure

After the code is compiled, the compiler discards the type information for the type parameters; therefore, this type information is not available at run time.

Java's generics are pseudo-generics. After compilation, the Java virtual machine cannot recognize the additional information of generics.

If the student class is a subclass of the people class, it is defined as follows:

  

At this time, we construct a method whose parameter is my of type List<people>, which appears to the virtual machine as a List type. If we pass a list of type List<student> to the function, the compiler will report an error ( Due to type erasure, the compiler has "disregarded" and does not know that student is a subtype of people)

solution

As shown above, since the type will be erased, no matter what type is used, only parameters of that type can be used as parameters. When should wildcards be used? When , lists of all types can be passed in, but at this time there cannot be operations involving parameter types in the method (jvm does not know the type of parameters).

Pay attention to the difference between before and after. The addition of extens indicates that only people and people subtypes can be passed in here. As shown in the figure below, a list of List<animal> type is passed in, and an error is prompted.

 Similarly, if only people and the parent class of people can be passed in, you need to add the super people modification:

static void fun(List<? super people> my){
        for(Object temp:my){
            System.out.println(temp);
        }
    }
    public static void main(String[] args) {
        List<creature> list=new ArrayList<creature>();
        fun(list);
    }

Source code

import java.util.ArrayList;
import java.util.List;

public class Compare {
    List<String> mylist=new ArrayList<>();
    static void fun(List<? super people> my){
        for(Object temp:my){
            System.out.println(temp);
        }
    }
    public static void main(String[] args) {
        List<creature> list=new ArrayList<creature>();
        fun(list);
    }
}
class creature{

}
class people extends creature{
    String name;
}
class animal extends creature{
    String name;
}
class student extends people{
    String school;

    public student(String school) {
        this.school = school;
    }
}

Guess you like

Origin blog.csdn.net/qq_16198739/article/details/125173218