Java type erase (Java Erasure mechanism)

Source: Internet
Author: User

Java provides generics (Java genertics) after JDK5, allowing the use of types as parameters when defining classes. Generics are widely used in various collections. This article describes it and its usage.

1. A common mistake

In the following example, a parameter of type list<object> is used to receive list<string>.

 public  class   Main { public  static  void  main (string[] args) throws   IOException {ArrayList  <String> al = new  Arrayl        Ist<string> ();        Al.add ( "a"  "B"  public  static  void  Accept (Arraylist<object> al) { for   (Object o:al) System.out.println (o); }}

It seems that object is the parent of string, and there is no problem. However, the compile time is not passed. The error is as follows:

for < String >)

2, list<object> vs list<string>

The reason is that the Java type Erasure mechanism is not compiled by the compiler to compile object and string type information when it is translated into class files. Therefore, in order to prevent errors, the compiler found that they are inconsistent at compile time will be error.

3. Wildcard and unbounded wildcard characters

Unbounded wildcard list<?> can receive any type

 Public Static voidMain (String args[]) {ArrayList<Object> Al =NewArraylist<object>(); Al.add ("ABC");    Test (AL); }      Public Static voidTest (arraylist<?>al) {         for(Object E:al) {//no matter what type, it would be ObjectSystem.out.println (e);//in the This method, because we don't know what type? are, we can not add anything to al.        }    }

Wildcard characters

list< Object >-List can contain object or it ' s subtypelist<? Extends number >-  List can contain number or its subtypes. list<? Super Number >-List can contain number or its supertypes.

  

Java type erase (Java Erasure mechanism)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.