Java-based generics

Source: Internet
Author: User
Tags java se

First, the introduction of generics

Generics are a new feature of Java SE 1.5, and the nature of generics is a parameterized type, meaning that the data type being manipulated is specified as a parameter. This type of parameter can be used in the creation of classes, interfaces, and methods, called generic classes, generic interfaces, and generic methods, respectively. The benefits of introducing generics into the Java language are simple and secure.
In the case of Java SE 1.5, without generics, the "arbitrariness" of arguments is implemented by reference to type object, and the disadvantage of "arbitrariness" is to make explicit coercion of type conversions, which require the developer to be able to predict the actual parameter type. In the case of coercion of type conversion errors, the compiler may not prompt for an error and an exception occurs at run time, which is a security risk.
The benefit of generics is that it checks for type safety at compile time, and all casts are automatic and implicit to increase the rate of reuse of the code.

Second, the application of the generic type

1. Generic type

Used in the definition of a class, is called a generic class. Generics enable the same interface to be opened for operations on a set of classes. The most typical is a variety of container classes, such as: List, Set, Map. A generic type parameter can only be a class type and cannot be a simple type. The instanceof operation cannot be used on the exact generic type. If the following operation is illegal, a compile-time error occurs.

1 //here t can be arbitrarily written as arbitrary identity, common parameters such as T, E, K, V, etc. are commonly used to denote generics2 //when instantiating a generic class, you must specify the specific type of T3  Public classGeneric<t>{ 4     //Key The type of this member variable is the T,T type specified by the external5     PrivateT key;6 7      PublicGeneric (T key) {//The type of the generic constructor method parameter key is also specified externally for type t,t8          This. Key =key;9     }Ten  One      PublicT GetKey () {//The type of the return value of the generic method Getkey type t,t is specified externally A         returnkey; -     } -}

2. Generic interface

is basically the same as the definition and use of generic classes. Generic interfaces are often used in a variety of class-based producers.

//define a generic interface Public InterfaceGenerator<t> {     PublicT Next ();}/*** When a generic argument is not passed in, it is the same as the definition of a generic class, and when declaring a class, it is necessary to add the declaration of the generic to the class as well * that is: class Fruitgenerator<t> implements generator<t>{* If you do not declare generics, such as: Class Fruitgenerator implements Generator<t>, the compiler will error: "Unknown class"*/classFruitgenerator<t>ImplementsGenerator<t>{@Override PublicT Next () {return NULL; }}/*** When passing in a generic argument: * Define a producer to implement this interface, although we only create a generic interface generator<t> * But we can pass in countless arguments for T, forming countless types of generator interfaces. * When implementing a generic interface for a class, such as when a generic type is passed into an argument type, all places that use generics are replaced with the passed argument type * i.e.: Generator<t>,public t Next (), and the T in is replaced by the incoming string type. */ Public classFruitgeneratorImplementsGenerator<string> {    Privatestring[] Fruits =Newstring[]{"Apple", "Banana", "Pear"}; @Override PublicString Next () {Random rand=NewRandom (); returnFruits[rand.nextint (3)]; }}

3. Generic method
Whenever you can do it, you should try to use a generic method. That is, if you use a generic method to generics the entire class, you should use a generic method. In addition, for a static method, you cannot access the parameters of a generic type. So if the static method is to use generic capabilities, you must make it a generic method.
Static methods One thing to note is that static methods in a class use generics: Static methods cannot access generics defined on a class, and if the reference data type of a static method operation is undefined, the generic must be defined on the method.

A generic class that indicates the specific type of a generic when the class is instantiated; a generic method that indicates the specific type of a generic when invoking a method

A static method must also be defined as a generic method if the static method is to use generics.

/*** Basic Introduction to generic methods *@paramtclass incoming generic argument *@returnThe t return value is t type * Description: * 1) public and return value intermediate <T> is very important and can be understood as declaring this method as a generic method. * 2) Only the method that declares <T> is a generic method, and a member method that uses generics in a generic class is not a generic method. * 3) <T> indicates that the method will use generic type T, at which point the generic type T can be used in the method. * 4) Like the definition of a generic class, here t can be arbitrarily written as arbitrary identity, common parameters such as T, E, K, V, etc. are commonly used to represent generics. */ Public<T> T Genericmethod (class<t> tclass)throwsinstantiationexception, illegalaccessexception{T instance=tclass.newinstance (); returninstance;} Public classGenerictest {//This class is a generic class that has been described above    Public classGeneric<t>{             PrivateT Key;  PublicGeneric (T key) { This. Key =key; }        //What I'm trying to say is this, although generics are used in the method, this is not a generic method. //This is just a normal member method in the class, except that his return value is a generic that declares that the generic class has already been declared. //Therefore, you can continue to use the generic type T in this method.          PublicT GetKey () {returnkey; }        /*** This method is obviously problematic, and the compiler will give us the error message "Cannot reslove symbol e" * Because the generic E is not declared in the class declaration, so when you use E to make formal parameters and return value types, the compiler will not recognize        。 Public E Setkey (e key) {This.key = Keu}*/    }    /*** This is a true generic method.     * First, the <T> between public and return values is necessary, which indicates that this is a generic method, and declares a generic T * this t can appear anywhere in this generic method.     * The number of generics can also be as many as: public <T,K> K showkeyname (generic<t> container) {* ... *} */     Public<T> T Showkeyname (generic<t>container) {System.out.println ("Container key:" +Container.getkey ()); //Of Course This example is not appropriate, just to illustrate the nature of the generic method. T test =Container.getkey (); returntest; }    //This is not a generic method, this is an ordinary method, just use the generic<number> generic class to do the formal parameters.      Public voidShowKeyValue1 (generic<number>obj) {LOG.D ("Generic Test", "key value is" +Obj.getkey ()); }    //This is also not a generic method, which is also a common method, except the use of generic wildcard characters? //This also confirms what the generic wildcard section describes, which is a type argument that can be considered as the parent of all classes such as number     Public voidShowKeyValue2 (generic<?>obj) {LOG.D ("Generic Test", "key value is" +Obj.getkey ()); }     /*** This method is problematic and the compiler will prompt us with an error message: "UnKnown class ' E '" * Although we declare <t>, it also shows that this is a generic method that can handle the type of generics.    * But only the generic type T is declared and the generic type E is not declared, so the compiler does not know what to do with the type E.      Public <T> T showkeyname (generic<e> container) {...} */    /*** This method is also problematic, the compiler will give us the error message: "UnKnown class T '" * for the compiler, the type of T is not declared in the project, so the compiler does not know how to compile this class.    * So this is not a proper generic method declaration. public void Showkey (T genericobj) {}*/     Public Static voidMain (string[] args) {}} Public classStaticgenerator<t> {    ....    ....    /*** If you define a static method that uses generics in a class, you need to add an additional generic declaration (define this method as a generic method) * Even if a static method is to use a generic type that has already been declared in a generic class.     * For example: public static void Show (T t) {..}, at which point the compiler will prompt the error message: "Staticgenerator cannot be refrenced from static context" */     Public Static<T>voidShow (T t) {}}

C. Generic wildcard characters

As mentioned earlier, Java introduced generics is for compile-time type checking, when declaring the specific type, in the use is no longer the strong type conversion, simple and secure. However, Java generics are only valid at compile time, and generic types are erased at run time. To reduce runtime type errors, Java stipulates that generic classes cannot pass inheritance relationships, even if a is a B parent class,list<a> or list<b> parent class, that is list<object> List = new arraylist< String> (); Failed to compile through. What if you really want to introduce a parent class and implement a similar inheritance operation? So the type wildcard "?" is introduced, representing the unknown type, which is the type argument, "?" is a wildcard character that can only be used in "<>" . wildcard characters can only appear in the referenced definition, not in the creation object. For example: New Arraylist<?> (), this is not possible. arraylist<?> list = null, which is possible.

such as list<?> list = new arraylist<string> (); List<?> can be thought of as the parent class of all classes such as list<string> ( note list<?> and list<object> are different, the former is an unknown type and can be seen as list< The parent class of string>, but list<object> is a deterministic type and cannot be used as a list<string> parent class , but because the list is of an unknown type, it cannot be considered as list<string > (Again, theparent class in Java cannot be treated as a subclass, only subclasses can be treated as a parent class ), List.add ("Hello") is illegal.

  New Arraylist<string>();        // List List = new arraylist<> ();       New Arraylist<object>();       List.add ("Hello"); // The list<?> type is unknown, the compilation does not pass, and the String class method       cannot be used List.add (null);

? Represents an infinite bound wildcard character, which can qualify wildcard characters on the upper or lower bounds (cannot qualify both upper and lower bounds), such as:

list<? Extends parentclass&interface1> restricts its parent class to be class ParentClass, and implements interface Interface1,list<? > is actually equivalent to list< Extends Object>, because the type uncertainty can not be to list< Add an object other than NULL in extends Parentclass&interface1>.

list<? Super Number> restricts the parent class whose bottom boundary must be number or number, but the inheritance and list<?> inheritance relationships of element types in list, at which point the subclass object of number can be added to the list.

Super number> list2 =new arraylist<>();       List2.add (new Integer (1));        // List2.add (New Object ()); // the parent class of number cannot be added without compiling;

Iv. Matters of note

In Java is "cannot create an array of the exact generic type"

New // Not really allowed.     Object o = LSA;     = (object[]) o;    ListNew arraylist<integer>();    Li.add (new Integer (3));    oa[//  unsound, but passes run time store check    //  run-time Error: ClassCastException.

Because of the JVM generic erasure mechanism, the JVM does not know the generic information at runtime, so it can give oa[1] a ArrayList without exception, but when the data is fetched, it is a type conversion, so there will be classcastexception, If you can make a declaration of a generic array, it says that there will be no warnings and errors at compile time, and only errors will occur at run time. Instead of restricting the declaration of a generic array, it is much better to have a type-safety problem with the code at compile time than to have no hint.

Java-based 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.