About the Java Erase feature

Source: Internet
Author: User

1  PackageThinkinginjava;2 /*3 * Simulated Erase4  */5  Public classSimpleholder {6     7     PrivateObject obj;8      Public voidset (Object o) {9obj =o;Ten     } One      PublicObject Get () { A         returnobj; -     } -      Public Static voidMain (string[] args) { the         //if the class uses a generic parameter, and the type of the obj variable is the type represented by the generic parameter, the type information is automatically erased when the object of the class is constructed. -         //for variable types with non-generic upper bounds converted to corresponding non-generic upper bounds, no specified is converted to object -Simpleholder demo =NewSimpleholder (); -         //the compiler throws all of the type information at run time, so the set method parameter does not work even if the generic is used. +         //Instead, it converts the converter to a non-generic upper bound, but when the object enters (through a generic set value) The object is judged to be consistent with the generic -Demo.set ("xxx") ; +         //Of course, the obtained value is also the corresponding non-generic upper bound type. But the compiler will automatically insert code that enforces type conversions AString x =(String) demo.get (); at     } -}

Package thinkinginjava;/* * Use generic version */public class Genericholder<t> {private T obj;p ublic void set (T t) {this.obj = t;} Public T get () {return obj;} public static void Main (string[] args) {genericholder<string> demo = new genericholder<string> ();//demo.set (New Object ()); Although all type information is dropped at run time, the compiler will still ensure that the arguments passed in are consistent with the generic Demo.set ("Hello"); String x = Demo.get (); The compiler automatically inserts a forced type conversion code when it comes out}}

  

About the Java Erase feature

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.