Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the Java type erasure mechanism

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report