What is the Java type erasure mechanism
This article mainly introduces "what is the Java type erasure mechanism". In the daily operation, I believe that many people have doubts about what the Java type erasure mechanism is. The editor consulted all kinds of data and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "what is the Java type erasure mechanism?" Next, please follow the editor to study!
Java generics, a feature introduced by JDK 5, allow us to use parameter types when defining classes and interfaces, and generics are widely used in collection frameworks. Type erasure is the most confusing part of generics.
A common mistake
Package simplejava;import java.util.ArrayList;public class Q29 {public static void main (String [] args) {ArrayList al = new ArrayList (); al.add ("a"); al.add ("b"); accept (al);} public static void accept (ArrayList al) {for (Object o: al) System.out.println (o);}}
The above code looks fine because String is a subclass of Object. However, this will not work, the compilation will not pass, and the following error will be prompted:
The method accept (ArrayList) in the type Q29 is not applicable for the arguments (ArrayList)
List and List
The reason is type erasure. Remember: Java's generics mechanism is implemented at the compile level. The bytecode generated by the compiler does not contain generic type information at run time.
After compilation, List and List become List,Object and String type information that is not visible to JVM. During the compilation phase, the compiler finds that they are inconsistent and gives a compilation error.
Wildcards and bounded wildcards
List