java-Basics-Generics

Source: Internet
Author: User

Java generic wildcard character problem. Generic basic usage in  java reference to "Java Programming Ideas" Fourth edition P.353java generics is more difficult to understand is the type erasure and wildcard correlation.  1. Type erasure during compilation, the type information is erased and it can be considered that the type detection is performed during compilation (see Example 1) list<string> List = new arraylist<> () List.add ("123" ); List.add (new Object ());//The compiler detects this type mismatch when compiling, so the generated class file does not contain the type information in generics. So the following code will error class test{public void Method1 (list<string> list) {System.out.println ("String list");} public void Method1 (list<integer> list) {System.out.println ("Integer list");}} Because of the type erasure, the parameters in Method1 list<string> and list<integer> will be erased to List so Method1 method signature is the same, so error. In addition, the type erase will erase to his first boundary, which can be understood by the following example: Class F{public void F () {}}class test{public static <T> void Method1 (T t) {T.F (); Error, unable to determine that the passed in parameter is an instance of Class F}public static <t extends f> void method2 (T t) {T.F ();//correct, because the compiler examines the parameter T as an instance of Class F or subclass F in the compilation period Therefore, the F () method can be called}}2. Type erasure and polymorphism consider the following example: public class Main1 {public static void main (string[] args) {F z = new Z (); Z.setvalue ("233" );}} Class f<t>{private T t;public void SetValue (T t) {System.out.println ("F ' s SetValue metHod called "); this.t = t;}} Class Z extends f<string>{@Overridepublic void SetValue (String s) {System.out.println ("Z ' s SetValue method called" ); Super.setvalue (s);}} Consider the SetValue method of Class F from the aspect of type erase after the actual signature of the type erase is public void SetValue (Object obj). So the predicted print result should be: F ' s SetValue method called the actual result for Z's SetValue method Calledf ' s SetValue method called, that is, the implementation of the subclass methods to override the parent class method. The reason for this is that the compiler generated a bridge method for us (Bridgemethod) to see what methods are in class Z by reflection: method[] Methods = Z.class.getdeclaredmethods (); for (method Method:methods) {System.out.print (Method.getreturntype (). Getsimplename () + "" + method.getname () + "("); parameter[] Parameters = Method.getparameters (); for (Parameter p:parameters) {System.out.print (P.gettype (). Getsimplename () + "");} System.out.println (")");} Print result: void SetValue (String) void SetValue (object)//bridge method actually calls the bridge method SetValue (object) overrides the method of the parent class, and then calls void SetValue in the method ( String). Bridge method content: void SetValue (Object str) {this.setvalue (String) str);} This implements the overlay. 3. Wildcard characters 3.1 upper bound  list<? Extends Animal> list;//indicates that this list reference can point to a generic parameterThe number is an instance of the list implementation of animal or its subclasses. This is not to say that the list container can add instances of animal or animal subclasses. The most difficult thing for me to understand when looking at Java generics is the problem with wildcards, which is not very well understood. Explain it through an example. Prerequisite: Class Animal{public void Walk () {}}class Cat extends Animal{}class Dog extends Animal{}class Alaska extends Dog{} p Ublic class Main2 {public static void main (string[] args) {list<cat> catlist = new arraylist<cat> (); list<dog> doglist = new arraylist<dog> (); testlist (catlist); testlist (doglist);} public static void Testlist (LIST&LT;? extends animal> List) {list.add (New Cat ());//Error List.add (new Dog ());//Error List.ad D (New Animal ())//error//correct for (Animal animal:list) {Animal.walk ();}}} Look at the above code, you should be able to understand. Assume that the declaration is list<? The list of extends animal> can be added Animal and its subclasses, then catlist and its subclasses can be added to catlist when the Testlist method is called, whereas Animal is declared to hold only instances of the cat class , the contradiction between the two, so declared as List<? The list of extends animal> cannot add Animal and its subclasses (because it is not possible to determine what the generic parameter of the received list parameter is). However, it can be determined that the object that is stored in the list passed to the Testlist method must be animal or its subclasses, so the list is iterated and received with animal. 3.2 Nether  list<? Super Dog> list//indicates that this list reference can point to the L of a generic parameter of Dog or its parent classAn instance of the IST implementation. This is not to say that the list container can add instances of the dog or dog parent class. Prerequisite: Class Animal{public void Walk () {}}class Cat extends Animal{}class Dog extends Animal{}class Alaska extends Dog{} p Ublic class Main2 {public static void main (string[] args) {testList1 (New arraylist<dog> ()); TestList1 (New Arraylis T<animal> ());} public static void TestList1 (LIST&LT;? Super Dog> List) {list.add (New Dog ()); List.add (new Alaska ()); List.add (new) iMAL ());//error for (Dog dog:list) {}//Error}}testlist1 method can accept an instance of the list implementation of the generic parameter for the dog or the Dog parent class (list<dog> or List<animal >), it is possible to add an instance of the dog class or the subclass of the dog class to the list in method TestList1, because you can determine that the list container passed to the TestList1 method can hold the parent class of dog or dog. However, it is not possible to determine which parent class is specific. Therefore, it is wrong to receive a list iteration with a dog reference. The conclusions in   articles are summary of personal thinking, not authority, error, omission, and correction.   Reference: http://blog.csdn.net/baple/article/details/25056169http://blog.csdn.net/eventqueue/article/details/48914435

java-Base-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.