Java Basics _ Generics

Source: Internet
Author: User

What is a generic type


Generics are provided to the Javac compiler to qualify the input types in the collection, let the compiler block illegal input in the source program, the compiler compiles a collection of type descriptions to remove the "type" information, the efficiency of the program is not affected, for parameterized generic types, getclass () The method return value is exactly the same as the original type. Because the compiled bytecode erases the generic type information, as long as you can skip the compiler, you can add other types of data to a generic collection, such as using reflection to get the collection, and then call the Add () method to


Genericdemo.java

 Public classGenericdemo { Public Static voidMain (string[] args) {//No generics are used, you can add data of any type ObjectList Nogrnerics =NewArraylist<>(); Nogrnerics.add (1); Nogrnerics.add ("Hello"); Nogrnerics.add ("1L"); Nogrnerics.add (NewGenericdomain (1L, "Generic")); //because generics are not used, it is necessary to know the data type of a data at a location and cast it when the data is fetched, otherwise an error occurs unless it is received with object. Integer integer = (integer) nogrnerics.get (0); System.out.println ("Integer =" +integer); //because you do not know the type of data in a location, you receive it with ObjectObject objIndex1 = nogrnerics.get (1); System.out.println ("OBJINDEX1 =" +objIndex1); Object objeIndex3= Nogrnerics.get (3); System.out.println ("OBJEINDEX3 =" +objeIndex3); //Although class properties can be known through class objects, isn't that too much of a hassle?? System.out.println ("objeindex3.getclass () =" +Objeindex3.getclass ()); //using genericsList<string> STRs =NewArraylist<>(); Strs.add ("STR1"); Strs.add ("STR2"); Strs.add ("STR3"); //because it specifies that only string types of data can be placed in this list, the error occurs when other types of data are placed here, because they cannot be loaded.//from a certain point of view, generics solve coercion type conversions, make data features more visible, and have consistency//Strs.add (1);String str = strs.get (0); System.out.println ("str =" +str); }}

To bypass compile-time generics and add non-generic type data: Genericdemo2.java

 Public classGenericDemo2 {/*** Program target, add an integer type of data to a list<string> generic array * *@paramargs*/     Public Static voidMain (string[] args) {List<String> STRs =NewArraylist<>(); Strs.add ("STR1"); Strs.add ("STR2"); Strs.add ("STR3"); Strs.add ("STR4"); //This is not added because the generic type is specified and there is no generic erase//Strs.add (New Integer (1));System.out.println ("Before add a Integer value:" +STRs); //Adding integer data to generics with reflection by the principle of generics erasing at run-timeClass<list<string>> clazz = (class<list<string>>) Strs.getclass (); Try {            //here, when using reflection to get the Add method, if the parameter type is specified as String.class,//The Add method is, Java.util.ArrayList.add (java.lang.String)//and we pass in an integer type of data, then obviously cannot add success, will throw Java.lang.NoSuchMethodExceptionClazz.getdeclaredmethod ("Add", String.class). Invoke (STRs,NewInteger (1)); //Here's the same reason, Java.util.ArrayList.add (Java.lang.Integer) but with int,//keep in mind that Java is a strongly typed language and there is no automatic boxing and unpackingClazz.getdeclaredmethod ("Add", Integer.class). Invoke (STRs, 2); //This is also incorrect because class<list<string>> specifies the String to be putClazz.getdeclaredmethod ("Add", Integer.class). Invoke (STRs,NewInteger (4)); //Ibid .Clazz.getdeclaredmethod ("Add",int.class). Invoke (STRs, 5); } Catch(Exception e) {e.printstacktrace (); } finally {            //Correct Practice            Try{Clazz.getdeclaredmethod ("Add", Object.class). Invoke (STRs, 3); System.out.println ("STRs =" +STRs); //only object can do it.Clazz.getdeclaredmethod ("Add", String.class). Invoke (STRs, "4"); System.out.println ("STRs =" +STRs); } Catch(Illegalaccessexception | IllegalArgumentException |invocationtargetexception| nosuchmethodexception |SecurityException e) {                //TODO auto-generated Catch blockE.printstacktrace (); }} System.out.println ("After add a Integer value:" +STRs); }    }

Java Basics _ Generics

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.