Initial knowledge of Java generics

Source: Internet
Author: User
Tags addall

1 type of the covariance group (covariant arrays type)

Covariance of arrays:

If A is-a B then a[] is-a b[]

That is, the array in Java is compatible, and an array of one type is compatible with his subclass type array.

Covariance group Benefits: makes the code more flexible.

The disadvantage of a covariance group: too flexible to cause type confusion, such as:

peron[] arr = new EMPLOYEE[5]; Employee is-a person can perform

Arr[0] = new Student ();//Student is-a person can execute

The above section of the program in the compiler to complete the compiler, all in the actual execution will be reported classcastexception exception, because Arr[0] is actually a reference to the employee type, but now the student type of the object assigned to it, the type is different therefore will report an error. As you can see, only array covariance that restricts type inheritance can cause confusion in data types.

2 pre-JAVA5 generic structural Properties widget

An important goal of object-oriented is to implement the reuse of code, and the generic mechanism can implement these methods only with a generic method when the different types have implementation methods. For example: Now we need to implement a simple class that requires only the command-line output of the input elements, and if the function's formal parameters are limited to string, then we can only enter elements of the output string type, Similarly, when an integer can only enter the integer type cannot enter the string type, otherwise will error, this can use their common parent class object, because of Java polymorphism, the subclass can be assigned to the parent class, so you can use only one object as a function of formal parameters, Each of these two types is handled separately.

Before Java5 introduces a generic mechanism, the program uses the superclass (the parent class of most pending types) Object when it is to implement generics.

The next section of code is:

 Public class memorycell{  public Object Read () {return  storevalue;}        Public void Write (Object x) {storevalue=x;
System.out.println ("storevalue=" +storedvalue); Private Object storevalue; }

This program uses the object class as the type of the Storevalue, and the type of the Wirte parameter, which, by the Java polymorphism mechanism, can pass in the object's subclass as an argument.

Class testmemorycell{public  static void Main (string[] args)  {     Memorycell mc  = new Memorycell ();     Mc.write ("32");//The subclass string of an object as an argument     mc.read ();//Output val=32
  
     Memorycell MC2  = new Memorycell ();     Mc.write (New Integer (343));//The subclass string of an object as the argument     mc.read ();//Output val=343
} {

Thus, we can tell the arbitrary shape as a string, such as a subclass of object, as an argument input to the function, to complete the printing function of the element.

3 JAVA5 proposed generic mechanism

Before Java5 people want to implement the Java mechanism all need to pass the above mechanism, are the above mechanism has some problems, when using object as a formal parameter inevitably brings the same problem as the group covariance-data type confusion. But what if the actual development requires Java to implement generic features to complete the reuse of the code? can only introduce new specifications Bai, just as everyone likes to do that.

Generics include generic classes and generic static methods.

3.1 Generic class

Form: Class ClassName <anytype1|,anytype2...>{...}//anytype

Instantiation of a generic class: Classname<string> cn = new Classname<string> (); or classname<string> cn = new Classname<> ();//string is just an example that can be used for other types, such as Integer

Note: AnyType can be defined as any string, including string, while the string is only used as a variable name, not a generic type as a string; AnyType: You can use it as a type in a class.

As can be seen, the generic class is the class name is added to the angle bracket, in angle brackets can be a type parameter. The same interface can also be defined as generics.

There is a significant difference between the generic mechanism of JAVA5 and the generic structure before JAVA5: Generics can remember the type of data, and element output of type object requires casting. Remembering data types also guarantees that the data type is determined at the time of data entry.

Advantages of using generics: ① by (2) You can know that generics can be reused for code;

② can detect errors that were originally run-time to be discovered at compile time. For example: array covariance, which also exists in generics prior to JAVA5, but can be used to make errors at compile time using generics.

  

3.2 Type wildcard characters

A simple generic class Memorycell:

Class Memorycell<x>{public X Read () {return storedvalue;} public void Write (x x) {storedvalue = x; System.out.println ("storedvalue=" +storedvalue); Private X StoredValue;}

  

Memorycell<string> and memorycell<object> are not two different classes?

Class Testmemorycell{public static void Main (string[] args) {memorycell<string> MC1 = new memorycell<string> (); memorycell<object> MC2 = new memorycell<object> (); System.out.println ("New memorycell<string> ()." classname== "+mc1.getclass ()); Output: New Memorycell<string> (). Classname==class MemoryCellSystem.out.println ("New memorycell<object> (). classname== "+mc2.getclass ()); Output: New Memorycell<object> (). Classname==class MemoryCellSystem.out.println (Mc1.getclass () ==mc2.getclass ());//output: true}}

It can be seen from the above program that memorycell<string> and memorycell<object> are the same class. This means that only one Memorycell class is retained in memory. Specifically how to implement data type limitations see this blog http://blog.csdn.net/yi_afly/article/details/52002594, Roar, is the use of invisible overloaded method (Java can not have a different return value of the overload, But the class here has two signatures, and the JVM makes a difference at run time.

Memorycell<string> is not a memorycell<object> subclass?

Class Testmemorycell{public static void Main (string[] args) {memorycell<string> MC1 = new memorycell<string> (); memorycell<object> MC2 = MC1; Error: Incompatible type: memorycell<string> cannot be converted to Memorycell<object>}}

If it is a subclass, that MC1 can be assigned directly to MC1, so it is not a subclass. But what is the parent of string when it is obvious that the object has no such relationship with the generic type? This is the intention of the designer, that is, do not want to appear at the beginning of the array covariance brought about by the compilation by the run time because the data type confusion and error.

Then assume that there are procedures as follows:

Class Testmemorycell{public static void Main (string[] args) {memorycell<string> MC1 = new memorycell<string> (); memorycell<object> MC2 = new memorycell<object> ();//system.out.println ("New memorycell<string> ()." classname== "+mc1.getclass ());//system.out.println (" New memorycell<object> (). classname== "+mc2.getclass ());//system.out.println (Mc1.getclass () ==mc2.getclass ());//memorycell<object> MC3 = mc1;mc1.write ("haha"); get (MC1);} public static void Get (Memorycell<object> MC) {System.out.println ("storedvalue=" +mc.storedvalue);}}

Then the program error: the incompatible type: Memorycell<string> cannot be converted to memorycell<object>. But we only need the ToString method of object, so strict restrictions will affect the flexibility of the program, so the type wildcard is proposed.

Type wildcard character:<?>//? Passed as an argument to a generic class

The wildcard character of type <?> means that it can be any wildcard character. So

The above program to make the following changes to smooth output

public static void Get (Memorycell<?> MC) {System.out.println ("storedvalue=" +mc.storedvalue);

3.2 Type wildcard upper limit, type wildcard lower limit, set upper limit of type parameter

Upper limit of type wildcard: Sometimes, we hope? Represents a class with a subclass of the same parent class, so that it can ensure the smooth execution of the parent class method, so the use of < Extends anytype> is that a requirement? Must be a subclass of Anytype.

Class Testmemorycell{public static void Main (string[] args) {memorycell<string> MC1 = new memorycell<string> (); memorycell<object> MC2 = new memorycell<object> () mc1.write ("haha"); get (MC1);//string Extens String Can execute Mc2.write ("aha"); get (MC2);//object is-not-a String error, incompatible type: memorycell<object> cannot convert to memorycell<? Extends string>}public static void get (MEMORYCELL<? extends String> MC) {System.out.println ("storedvalue=" + Mc.storedvalue);}}

can also define the lower bound, <? Super anytype>? must be the parent class for AnyType.

In the definition of a class, you can also set the upper bound of a type parameter, which restricts the parameters that are passed in when the instance is created.

4 Java5 Generic method

When do you want to use a generic method?

You do not use a type parameter when defining a class, an interface, but you want to define a type parameter when you define the method, which is a generic method that needs to be JAVA5 provided.

4.1 Defining a generic static method

 

Class genericmothod{   static void Fromarraytocollection (object[] a,collection<object> c)   {for         ( Object o:a)               c.add (o);    }    public static void Main (String [] args)   {         string[] Strarr = {"A", "B"};          list<string> strlist = new arraylist<> ();         Fromarraytocollection (Strarr, strlist);//Compile error, unable to convert collection<string> to collection<object>          }}

The previous code compilation failed because collection<string> is-not-a collection<object>, but if you use an array instead of a collection, you can do so without an error, because the array has covariance. Does this not mean that generics can be a great inconvenience, or that it reduces the reusability of code, because to use collection<string> you have to redefine a function, using Java's method overloads. So JAVA5 proposed a new generic method.

Generic method format: modifier <T,S> return type method name (formal parameter list) {...} Define one or more type parameters when defining the method;

So the fromarraytocollection of the above procedure can be changed into the following form:

  

  
ImportJava.util.*;classgenericmethod{Static<T>voidFromarraytocollection (t[] a,collection<t>c) { for(T o:a) C.add (o); }     Public Static voidmain (String [] args) {string[] Strarr= {"A", "B"}; Object[] STRARR2= {"A", "B"}; List<String> strlist =NewArraylist<string>(); List<Object> StrList2 =NewArraylist<object>(); Fromarraytocollection (Strarr, strlist);//compiled byFromarraytocollection (STRARR2, strList2);//compiled by    }}

It can be seen from this program that a generic method differs from a generic class in that the formal parameters of a generic method do not need to be displayed in the actual arguments, but rather the type parameters are inferred from the Fromtocollection (Strarr, strlist) compiler based on the argument type. So what if the type parameters inferred from the previous and the two arguments are inconsistent? Then compile a natural error. For example:

ImportJava.util.*;classgenericmethod{Static<T>voidFromarraytocollection (t[] a,collection<t>c) { for(T o:a) C.add (o); }     Public Static voidmain (String [] args) {string[] Strarr= {"A", "B"}; Object[] STRARR2= {"A", "B"}; List<String> strlist =NewArraylist<string>(); List<Object> StrList2 =NewArraylist<object>(); Fromarraytocollection (Strarr, strlist);//compile error, cannot distinguish T typeFromarraytocollection (Strarr, strList2);//compile without error, T is Object    }}

A generic method can also use a type parameter wildcard, for example:

Static void Test (Collection <? extend T>from,collection<t> to ) {    for(T ele: From)        staticvoid  main (string[] args) {   List<Object> ao =New arraylist<>();   ListNew arraylist<>();    // The T is judged as object and compiled by. }

5 The difference between a generic method and a type wildcard

1 //type of collection interface wildcard method definition2  Public InterfaceCollection<e>3 {4     BooleanContainsall (collection<?>c);5     BooleanAddAll (collection<? Extend e>c);6     ...7 }8 //generic function mode definitions for collection interfaces9  Public InterfaceCollection<e>Ten { One<T>BooleanContainsall (collection<t>c); A<textendsE>BooleanAddAll (collection<t>c); -     ... -}

As can be seen from the above example, generic methods and type wildcards can achieve the same functionality. So when do we use generic methods?

Use generic methods: A run-type parameter is used to represent a dependency between one or more parameters of a method, or a relationship between a return value and a parameter. If this relationship does not exist, you should use a type wildcard.

A significant difference between a generic method and a type wildcard: A type wildcard can define a formal parameter type in a method signature, or it can be used to define the type of a variable, but the type parameter of a generic method must display a description in the corresponding method.

6 Limitations of generics

Because generic classes become non-type classes in the compiler through type erasure (a generic class mentions that a generic class has only one non-generic class in memory), there are limitations on generics definitions.

① base type cannot be a type parameter

②instanceof detection cannot be used on generic classes

③ class-Variable class methods that are static decorated in a generic class cannot refer to the type arguments of the class, because type arguments do not exist and are shared when the static variable is present in the generic instance because there is only one original class.

④ generic type variables cannot be instantiated

⑤ There is no generic type of array

⑥ is illegal when instantiating an array of parameterized types.

  

Reference:

1. "Data structure and algorithm analysis Java description"

2.Java Summary series: Java generics http://www.cnblogs.com/lwbqqyumidi/p/3837629.html

3. "Crazy Java Handout" chapter Nineth generics

Initial knowledge of Java generics

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.