Java generics: Type erase

Source: Internet
Author: User

Type Erase code fragment one
New arraylist<integer>new arraylist<string>= = C2); /* outputtrue */

Obviously in the normal use, ArrayList<Integer>() and new ArrayList<String>() is completely different types, but here, the program does indeed output true .

This is caused by the type erasure of Java generics, because either ArrayList<Integer>() or new ArrayList<String>() both of the compilers are erased by the compiler ArrayList . Why did the compiler do it? The reason is the same as most Java's annoying point-compatibility. Since generics are not a feature that exists from the birth of Java, they wait until SE5 is joined, so in order to be compatible with generic class libraries and code, you have to let the compiler erase parts of the code that have information about generic types, so that the resulting code is actually "generic-independent". When we use someone else's code or class library, we don't have to worry about whether the code is "generalized" or vice versa.

This is done at the compiler level (erasing specific type information), which makes Java generics inherently a very uncomfortable disadvantage:

Inside the generic code, you cannot get any information about the generic parameter types.
Code fragment Two
New Arraylist<integer>(); MapNew Hashmap<integer, string>(); System.out.println (Arrays.tostring (List.getclass (). Gettypeparameters ())); System.out.println (Arrays.tostring (Map.getclass (). Gettypeparameters ())); /* output[e][k, V] */

About getTypeParameters() the explanation:

 This if the underlying generic declaration declares no type variables.

We expect to get the type of the generic parameter, but in fact we only get a bunch of placeholders.

Code Snippet Three
 Public class Main<t> {    public  t[] Makearray () {        //  error:type parameter ' T ' cannot be instantiated directly        returnnew t[5];     }

We cannot create an array of types inside a generic, for the T same reason as before, T just a placeholder, and there is no real type information, in fact, in addition to new expressions, instanceof Operations and Transformations (which will receive a warning) are not available within generics. The reason for this is that the compiler has previously talked about erasing the type information.

At the same time, in the face T var; of the generic internal shape of the code, remember to read a few times: it is just an object, it is just an object ...

Code Snippet Four
 Public classMain<t> {    PrivateT T;  Public voidset (T t) { This. T =T; }     PublicT Get () {returnT; }     Public Static voidMain (string[] args) {main<String> m =NewMain<string>(); M.set ("Findingsea"); String s=M.get ();    System.out.println (s); }}/*Outputfindingsea*/

Although there is a type erase, the compiler does not know anything about it in the generics, T but the compiler can guarantee an important point: internal consistency, what type of object we put in, whether it's out of the same type of object, This makes Java generics at least useful.

Snippet four shows that the compiler ensures that the type we put t on is indeed T (even if it doesn't know T any type of information about it). This ensures that two steps are actually done:

    • set()Type inspection at the

    • get()Type conversion at the

This two-step work also becomes the border action.

Code Snippet Five
 Public classMain<t> {     PublicList<t> filllist (T T,intsize) {List<T> list =NewArraylist<t>();  for(inti = 0; i < size; i++) {List.add (t); }        returnlist; }     Public Static voidMain (string[] args) {main<String> m =NewMain<string>(); List<String> list = m.filllist ("Findingsea", 5);    System.out.println (List.tostring ()); }}/*Output[findingsea, Findingsea, Findingsea, Findingsea, Findingsea]*/

Code snippet Five also shows the internal consistency of generics.

Compensation for Erase

As seen above, however, any operation involving the exact type of information is not common within generics. Is there a way to program around this problem, and the answer is to pass the type label to the display.

Code Snippet VI
 Public classMain<t> {     PublicT Create (class<t>type) {        Try {            returntype.newinstance (); } Catch(Exception e) {e.printstacktrace (); }        return NULL; }     Public Static voidMain (string[] args) {main<String> m =NewMain<string>(); String s= M.create (String.class); }}

Code Snippet VI shows a way to generate a new object with a type tag, but this approach is fragile because it requires that the corresponding type must have a default constructor, Integer fails when encountering a type, and that the error cannot be captured by the compiler.

The advanced method can be used to improve this problem with the restriction type display factory and template method design pattern, which can be found in the Java Programming Idea (4th edition) P382.

Code Snippet Seven
 Public class Main<t> {    public t[] Create (class<t> type) {        return (t[]) Array.newinstance (type, ten);    }      Public Static void Main (string[] args) {        mainnew main<string>();         = M.create (String.  Class);}    }

Code Snippet VII shows the erase compensation for a generic array, and the essential method is to generate the array by displaying the type label, and it is also the Array.newInstance(type, size) most recommended method of generating an array inside a generic type.

Above, the end of the second part of the generics.

Java generics: Type erase

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.