"Xu Xu Daolai java": The basic concept of generics (1)

Source: Internet
Author: User

generics are a type of Programming Paradigm ( Programming Paradigm)is produced for efficiency and Reusability. first proposed by Alexander Stepanov(main designer of the C + + standard Library) and David Musser (rensselaer Institute of technology), since its inception, it has become one of the important standards of Ansi/iso C + +.

Java has been providing generics since version 1.5, which is essentially a parameterized type, so what is parameterization?

The parameter is an external variable. Imagine a method whose name and actual numeric value are externally passed in, and whether the type of the parameter is also used as an argument at run time? This is the role of Generics. Refer to the following code:

list<string> list = new arraylist<string> ();

List. Add (1);

in Line 2 , a compile-time error is thrown.

The method add (int, String) in the type list<string> are not applicable for the arguments (int)

This is becausethe list defines the type that the string needs for itself when declaring it, and 1 is an integer number. In the example above, the following additions are Legal:

List.add ("string");

List.add (new String ());

String str= "strings";

List.add (str);

in the In previous versions of j2se1.5, Java had no way of explicitly compiling a container for a compile-time content restriction, which was prone to runtime errors without comments or document Descriptions. Here is an example of the error:

ArrayList list = new ArrayList();

List.add (0);

List.add (1);

list.add (' 2 ');

List.add (3);

output list contents

System. Out. println (list);

traversing the output list contents

for (int i = 0, len = list.size (); i < len; i++) {

Integer Object = (integer) list.get (i);

System. Out. println (object);

}

The output results are as follows:

[0, 1, 2, 3]

0

1

Exception in thread "main" java.lang.ClassCastException: Java.lang.Character cannot is cast to Java.lang.Integer

At Capter3.generic.Generic3_1.test2 (generic3_1.java:28)

At Capter3.generic.Generic3_1.main (generic3_1.java:17)

as can be seen, the direct output of the list, the int type of 1 and Char type 2 is not see the difference, assuming that this is ignored, the direct conversion to integer to use, thrown a forced conversion exception.

in addition to causing the exception, you can also think of a problem, if there is no generic, then the List.get (int) method returns is always an object, then how to determine its type outside the runtime?

In conclusion, it has been proved that the necessity of the existence of generics, which provides the following capabilities:

1, Avoid coercion type conversion in the code;

2, the limit type, at compile time provides an additional type check, avoids the wrong value to be deposited in the container;

3, implement some special programming skills. For example, a method is provided to copy an object, keeping the return value type consistent with the method parameter type without providing additional method Parameters.

classification of generic types

Depending on how you use generics, you can divide into generic interfaces, generic classes, and generic methods. They are defined as Follows:

1. generic interface : After the interface name defined by the interfaces with the < generic parameter name, a generic interface is defined, and the scope of the generic parameter name exists within the interface definition and the entire interface body;

2. generic class : The class name defined by the class is followed by the < generic parameter name, and a generic class is defined, and the scope of the generic parameter name exists within the class definition and the entire class body;

3. Method Class : Precede the return value of the method with the < generic parameter name; a generic method is defined, and the scope of the generic parameter name includes the method return value, the method parameter, the method exception, and the entire method body.

below An example of how to define these types of generics is presented Separately. , the sample code is as follows :

/**

 * after normal interface with < generic parameter name > You can define a generic interface

 */

Interface  GenericInterface<T> {

}

 

/**

 * after the class definition with the < generic parameter name > to define a generic class, note the following genericinterface<t> here is the generic parameter of the class, not the Definition.

 */

class  GenericClass<T> implements   genericinterface<t>{

/**

 * The method that defines the generic parameter before the value is returned, that is, the generic method.

 */

public  <k, E extends  Exception> K Genericmethod (K Param) throws  e {

java.util.list<k> list  = new  ArrayList<K> ();

K k  = null ;

return   null ;

}

}

In the example above,There are two places in class Genericclass<t> implements genericinterface<t> that use <t> are they the same concept? To answer this question, here are a few basic concepts that will solve most of the similar generic problems by mastering these basic concepts.

a, class (interface ) of the generic definition location immediately after the class (interface) definition, You can override the class (interface) defines any type that is Inside. When the class (interface) is declared, the generic parameter is Determined.

b, the Method's generic definition position can override any type used in the method, including return values, parameters, and local variables, before returning a value after the Modifier. When the method is called, the generic parameter is determined, in general, by the method parameter to determine the generic parameter.

c, the emergence of <> there are two cases, one is to define generics, and the other is to use a class \ interface to the representational generics.

based on a few basic concepts described above, the code for class genericclass<t> Implemenets genericinterface<t> is Analyzed. It is known that class Genericclass is the definition of classes, then the first <T> constitutes the definition of a generic parameter, and the interface genericinterface is defined elsewhere, The code location is a reference to this interface, so the second <T> The generic t is used to standardize the genericinterface.

Extended:

If the generic method does not have formal parameters, is there any other way to specify the type parameter?

Answer: there are methods to specify, but this syntax is not common, the implementation code is as Follows:

genericclass<string> gc=new genericclass<string> ();

Gc.<string>genericmethod (null);

you can see a very special code form here,Gc.genericmethod (null) in the middle of an extra <string>, this is the Genericmethod method for the generic parameter Definition.

definition of a bounded generic

The bounded generics have three very important keywords :?, extends and Super.

A) "?", which denotes a wildcard type, is used to express any type, it is important to note that it refers to "an arbitrary type", but not an object; (note that this is not an exact expression, the exact content will be "invariant in generics" Related sections to Discuss)

The sample code is as follows :

class Parent {

}

class Sub1 extends Parent {

}

class Sub2 extends Parent {

}

class wildcardsample<t> {

T obj;

void Test () {

wildcardsample<parent> sample1 = new wildcardsample<parent> ();

Compile error

wildcardsample<parent> sample2 = new wildcardsample<sub1> ();

Normal compilation

wildcardsample<?> sample3 = new wildcardsample<parent> ();

wildcardsample<?> sample4 = new wildcardsample<sub1> ();

wildcardsample<?> sample5 = new wildcardsample<sub2> ();

Sample1.obj = new Sub1 ();

Compile error

Sample3.obj = new Sub1 ();

}

}

These codes reflect the role of WILDCARDS.

1. When using parent as a generic parameter in the Sample2 declaration, you cannot point to an instance that uses Sub1 as a generic parameter. Because the compiler handles generics strictly by definition, Sub1 is a subclass of the parent, but it is not a parent after All.

2, Sample3~5 Declaration of use? as a generic parameter, you can point to any wildcardsample instance.

3. Sample1.obj can point to an Sub1 instance, because obj is considered a parent, and Sub1 is a subclass of the parent that satisfies the upward transformation.

4, Sample3.obj cannot point to the SUB1 instance, because the wildcard character is "a type" and not an object, so Sub1 is not a subclass, throwing a compile-time error.

5, Although there are so many restrictions, but you can still use the object type to read sample3.obj, after all, regardless of the wildcard character is what type, object must be its parent class.

Extension: Imagine if sample3.obj = new Sub1 () can be compiled through, in fact the desired sample3 type is wildcardsample<object>, so the wildcard will lose meaning. in practice, This is not simply a loss of meaning, but it also causes an execution Exception. Here is an example to help understand:

wildcardsample<parent> sample1 = new wildcardsample<parent> ();

Sample1.obj = new Parent ();

wildcardsample<?> extsample = sample1;

Should be limited to the parent type, where a string type is used and an exception must be Thrown.

Extsample.obj = new String ();

B) extends is not an inheritance in generics, but an upper bound meaning, such as T extends Upperbound,upperbound is the upper bound of a generic t, which means t must be upperbound or its subclasses;

The generic upper bounds can be used to define and declare code at different locations when used, and it works differently for the use of methods , as shown in the sample code :

/**

* Generic class with upper bounds

*/

class Extendsample<t extends parent> {

T obj;

/**

* A generic method with upper bounds

*/

<k extends sub1> T Extendmethod (K Param) {

return This. obj;

}

}

public class Generic3_1_2_b {

public Static void main (string[] Args) {

extendsample<parent> sample1 = new extendsample<parent> ();

extendsample<sub1> sample2 = new extendsample<sub1> ();

extendsample<? extends parent> sample3 = new extendsample<sub1> ();

extendsample<? extends Sub1> sample4;

Compile error

Sample4 = new extendsample<sub2> ();

Compile error

extendsample<? extends number> sample5;

Sample1.obj = new Sub1 ();

Compile error

Sample3.obj = new Parent ();

}

}

In this example, a generic method with an upper bound and a generic class with an upper bound are used , which embody the application of extends in generics:

1, when the method \ interface \ Generic definition of the class, you need to use a generic parameter name (such as T or k).

2 . When you use a generic parameter in a declaration location, you need to use a wildcard character, meaning " to specify the upper bound of the class ( the class or its subclasses)."

Even if the upper bound is added, the object defined using wildcard characters is read-only and cannot be Written. The reason is already demonstrated in the relevant section of the wildcard, not to repeat it.

C) The Super keyword is used to define the lower bound of a generic type. such as T Super lowerbound, then lowerbound is the lower bound of the generic t, which means t must be lowerbound or its parent class;

The generic nether can only be applied to the declaration code, indicating that the generic parameter must be a specified class or its parent class.

Refer to the following code:

class supersample<t> {

T obj;

}

public class Generic3_1_2_c {

public Static void main (string[] Args) {

supersample<? Super parent> sample1 = new supersample<parent> ();

Compile error

supersample<? Super parent> sample2 = new supersample<sub1> ();

supersample<? Super sub1> sample3 = new supersample<parent> ();

Sample1.obj = new Sub1 ();

Sample1.obj = new Sub2 ();

Sample1.obj = new Parent ();

Sample3.obj = new Sub1 ();

Compile error

Sample3.obj = new Sub2 ();

Compile error

Sample3.obj = new Parent ();

}

}

In this example, you can notice that:

1, Sample1.obj must be the parent or father of parents, then, Sub1\sub2\parent can meet the upward Transformation.

2, sample3.obj must be Sub1 or SUB1 parent class, parent and SUB2 can not fully meet the conditions, so thrown an exception.

Extension: think of a question, what type of sample1.obj is in the above example?

Answer : Extends Parent, that is, no type.

Through the analysis of the above phenomena, we can see that when the upper bounds of extends are used, all methods that use the generic parameter as formal parameters are not available, and when the Super Nether is used, all methods that use the generic parameter as the return value Can only be referenced by object Type.

thinking : <, extends t> and <, what's The difference between Super t> ?

Define complex generics

Complex generics are also composed of simple generics that require the following concepts:

1, multiple generic parameter definitions are separated by commas, like <T,K>.

2. If there are multiple upper bounds for the same generic parameter, the & symbol is used to connect each upper Bound.

3, more than the upper bound type can have at most one class, the other must be an interface, if there is a class in the upper bound, it must be placed in the first place.

Combined with the above knowledge, it is possible to combine complex generic declarations flexibly. Refer to the following code:

class A

}

class B extends A {

}

class C extends B {

}

/**

* This is a generic class

*/

class Complexgeneric<t extends A, K extends B & Serializable & cloneable> {...}

As can be seen from the above code, the Complextgeneric class has two generic parameter <t,k>, where T has an upper bound a, in other words, T must be a or its subclasses, K has three upper bounds, respectively, class b, interface serializable and cloneable, In other words, K must be B or its subclass, and serializable and cloneable are Implemented.

Complex generics provide the possibility for more prescriptive and more precise designs.

Extension: as stated earlier, generics are processed as upper bound types at run Time. In other words, when a complextgeneric is used inside a generic t, the reflection treats it as a class (it is important to note that in the bytecode, or as an object), then the reflection is used when the generic k? The answer is that it is treated as the first upper bound of the upper bound definition, in the current example, the class B.

What's the point of knowing this?

Imagine a method <t extends a> void method (t t);

If you need reflection to get it, you must know both the method name and the parameter Type. At this point, the use of object is not found, and can only be obtained through Class A.

"Xu Xu Daolai java": The basic concept of generics (1)

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.