Generics in Java

Source: Internet
Author: User

1. Generics Overview

Generic, which is the parameterized type. When referring to a parameter, it is most familiar to define the method when the physical parameter is called and then pass the argument when calling this method. So how do parameterized types understand? As the name implies, the type is parameterized by the original specific type, similar to the variable parameter in the method, when the type is also defined as a Parameter form (which can be called a type parameter), and then the specific type (type argument) is passed in when using/calling.

The essence of generics is to control the type of the formal parameter restriction by the different types specified by the generic type, without creating a new type. That is, during generics use, the data type of the operation is specified as a parameter, which can be used in classes, interfaces, and methods, respectively, as generic, generic, generic.

This code is written before generics (Generic type or generics) appear:

public static void Main (string[] args) {    list list = new ArrayList ();    List.add ("123");    List.add ("456");        System.out.println (String) list.get (0));}

Of course, this is entirely permissible, because the contents of the list is object type, naturally any object type can be put in, can be taken out, but there are two problems in writing:

1. When an object is put into a collection, the collection does not remember the type of the object, and when the object is fetched again from the collection, the object's compilation type becomes object

2, the operation of the need to artificially cast the type to the specific target, the actual program will never be so simple, a careless will appear java.lang.ClassCastException, that is, type conversion exception

So, after the generics appear, the above code is changed to the familiar wording:

public static void Main (string[] args) {    list<string> List = new arraylist<string> ();    List.add ("123");    List.add ("456");        System.out.println (list.get (0));}

This is the generic type.

The introduction of generics is a major feature enhancement for the Java language, bringing a number of benefits:

1, type safety. Type errors are now captured during compilation, rather than being shown as java.lang.ClassCastException at run time, moving type checking from runtime to compile to help developers find errors more easily and improve program reliability

2, eliminate many of the code coercion type conversion, enhance the readability of the Code

3. Generic type parameters make our programs more readable and secure

2. The principle of generics

Look at a piece of code

public static void Main (string[] args) {    list<string> stringlist = new arraylist<string> ();    list<integer> integerlist = new arraylist<integer> ();    System.out.println (stringlist.getclass () = = Integerlist.getclass ());}

The result of the operation is:

True

This means that what generics are does not affect the type of an object instance. That is, generic information is not entered into the runtime of the code.

Because, during compilation, all generic information is erased by the,list<integer> and list<string> types, and after compilation it becomes the List type (the original type). Generics in Java are basically implemented at the compiler level, which is why Java generics are called Pseudo generics.

In a nutshell: generic types are logically viewed as multiple different types, and are essentially the same basic types.

3. Use of generics

Generics are available in three ways: generic class, generic interface, generic method

3.1 Generic class

A generic type is used in the definition of a class, which is referred to as 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.

Define one of the most common generic classes:

Here t can be arbitrarily written as arbitrary identity, common such as T, E, K, V and other forms of parameters commonly used to denote generics//When instantiating a generic class, you must specify the specific type of T public class generic<t>{     //key The type of the member variable is t , the type of T is specified by the external      private T key;    Public Generic (T key) {///Generic constructor method parameter key type also for t,t type is externally specified        This.key = key;    }    Public T GetKey () {///generic method GetKey The return value of type T,t type is specified by external        return key;    }}

A generic type parameter can only be a class type (including a custom class), not a simple type

The input argument type needs to be the same as the type parameter type of the generic, i.e. integer.generic<integer> Genericinteger = new generic<integer> (123456);// The input argument type needs to be the same as the type parameter type of the generic, i.e. string.generic<string> genericstring = new Generic<string> ("Key_vlaue"); SYSTEM.OUT.PRINTLN ("Generic Test: Key is" + Genericinteger.getkey ()); SYSTEM.OUT.PRINTLN ("Generic Test: Key is" + Genericstring.getkey ());
注意:
1.泛型的类型参数只能是类类型,不能是基本数据类型。
2.不能对确切的泛型类型使用instanceof操作,如下面的操作是非法的,编译时会出错。
if(ex_num instanceof Generic<Number>){   }

3.2 Generic interface

Generic interfaces are basically the same as the definition and use of generic classes. See an example:

Defines a generic interface public interface generator<t> {public    T next ();}

Implementation class, when a generic argument is not passed in:

/** * When a generic argument is not passed in, the definition of the generic class is the same as when declaring the class, the declaration of the generic must be added to the class together * i.e.: 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" */class fruitgenerator<t> Implements generator<t>{    @Override public    T Next () {        return null;}    }

To implement a class, when passing in a generic argument:

/** * When a generic argument is passed in: * Defines 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 class Fruitgenerator implements generator<string> {    private string[] fruits = new string[]{"Apple", "B Anana "," Pear "};    @Override public    String Next () {        random rand = new Random ();        Return Fruits[rand.nextint (3)];}    }
3.3 Generic wild-letter wildcard

We know Ingeter Number of a subclass, so can you use an instance of it in a Generic<Number> method that is used as a formal parameter Generic<Ingeter> ? Is it logically similar to Generic<Number> and Generic<Ingeter> can be seen as a generic type with a parent-child relationship?

We use Generic<T> this generic class to continue to look at the following example:

public void showKeyValue1 (generic<number> obj) {    System.out.println ("Generic test: Key value is" + Obj.getkey ());}

generic<integer> Ginteger = new generic<integer> (123); generic<number> gnumber = new generic<number> (456); Showkeyvalue (gnumber);// Showkeyvalue This method compiler will give us an error:generic<java.lang.integer>//cannot be applied to generic<java.lang.number> Showkeyvalue (Ginteger);

By prompting the message we can see Generic<Integer> `Generic<Number> the subclass that cannot be considered as. It can be seen that the same generic can correspond to multiple versions (because the parameter types are indeterminate), and that different versions of generic class instances are incompatible.

Back to the example above, how to solve the above problem? It is not always possible to define a new method to handle Generic<Integer> the class of a type, which is obviously contrary to the polymorphic idea in Java. So we need a reference type that can logically represent both Generic<Integer> and the Generic<Number> parent class. This type of wildcard character comes into being.

We can change the method above:

public void showKeyValue1 (generic<?> obj) {    System.out.println ("Generic test key value is" + Obj.getkey ());}

Type wildcard characters are generally used? Instead of specific type arguments, note that here '? ' is a type argument, not a type parameter . It's important to say three times! here '? ' is a type argument, not a type parameter ! here '? ' is a type argument, not a type parameter !

What's more straightforward is, here? As with number, String, and Integer, it is an actual type, and the <?> is a type wildcard that represents the parent type of any generic and is a true type .

Can be resolved when the specific type is uncertain, this wildcard is ? When an operation type is not required to use the specific functionality of the type, only the functionality in the object class is used. So you can use it? Wildcard character table unknown type.

3.4 Generic methods

A generic class that specifies the specific type of a generic when it instantiates a class, and a generic method that indicates the specific type of the generic when the method is called .

/** * Basic Introduction to generic methods * @param tclass incoming generic argument * @return 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 (T t) {        return T;}

Note: Generic methods are easily misunderstood, and here's a summary of what the real generic method is:

public class Generictest {//This class is a generic class, the public class generic<t>{private T key has been introduced above;        Public Generic (T key) {this.key = key;        }//What I want 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.        Public T GetKey () {return key; }/** * This method is obviously problematic in that the compiler will give us the error message "Cannot reslove symbol e" * Because the generic E is not declared in the declaration of the class, so when using E to do the formal parameter and return value type, the        The translator will not be recognized.     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:" + Contai        Ner.getkey ());        Of course This example is not appropriate, just to illustrate the nature of the generic method. T Test= Container.getkey ();    return test;    }//This is not a generic method, this is an ordinary method, just using the generic<number> generic class to do the formal parameters.    public void showKeyValue1 (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 seen as the parent of all classes, such as number, public void showKeyValue2 (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&gt, it also shows that this is a generic method that can handle the type of the generic type.    * 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 prompt us with 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 void main (string[] args) {}}

A generic method can also be defined as a mutable parameter:

Public <T> void printmsg (t ... args) {    for (t T:args) {        log.d ("Generic Test", "T is" + t);    }}

3.5 Static and generic

Class Test<t>{public static list<t> List;  Error public static void show (T t) {..}, at which point the compiler will prompt for a fault message: Staticgenerator cannot be refrenced from static context "}

This means that static does not actually know generics, so when defining a static method, the method is defined as generic, preceded by a static modifier.

public static <T> t show (T t) {...}

Sum up: No matter static method, static variable, static block do not know the generic type, the unity of statically resources do not know generics.

Load Address: http://blog.csdn.net/s10461/article/details/53941091

http://blog.csdn.net/sunxianghuang/article/details/51982979

Http://www.cnblogs.com/xrq730/p/4869134.html

Generics in Java

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.