Beginners learn Java (22)--Re-understanding generics

Source: Internet
Author: User
Tags comparable java se

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.


Rules and restrictions

1. A generic type parameter can only be a class type (including a custom class) and cannot be a simple type.
2, the same generic can correspond to multiple versions (because the parameter type is indeterminate), different versions of the generic class instances are incompatible.
3, generic type parameters can have more than one.
4. Parameter types of generics can use extends statements, such as <t extends Superclass>. It is customary to call it "bounded type".
5. The parameter type of a generic type can also be a wildcard type. For example class<?> ClassType = Class.forName ("java.lang.String").


Restricting generics
We typically define generics in this way: class Generics<t> in fact, the qualified type here is equivalent to object, which is the same as the "object generic" substance. What are limitations such as we want to limit T to the set interface type. You only need to do this: class Generics<t extends Collection>, so generic T in a class can only be an implementation class for the Collection interface, and an error occurs when the incoming non-Collection interface compiles.

Note: The <t extends collection> here is limited to using the keyword extends, which can be either a class or an interface. But the extends here is not the meaning of the inheritance, it should be understood that the T type is the type that implements the collection interface, or T is the type that inherits the XX class.


public class Collectiongen<t extends collection> {private T t;public Collectiongen (T t) {this.t = T;} Public T Gett () {return t;} public void sett (T t) {this.t = t;} public static void Main (String args[]) {collectiongen<arraylist> genlist = Null;genlist = new Collectiongen<arra Ylist> (New ArrayList ());//The following code cannot be compiled//collectiongen<collection> gencollention = null;//gencollention=new Collectiongen<arraylist> (New ArrayList ()); System.out.println ("Can compile through and run!");}}

The above code can be compiled and run successfully. However, opening the commented out two lines is wrong, because <t extends collection> so defined type, it is limited to construct such an instance of the time T is a certain type, this type implements the Collection interface. The simple sentence is: In this way, the definition and the type of instantiation must be exactly the same.


Wild-Wildcard generics
In order to solve the disadvantage that the type is limited to dead and cannot be determined dynamically based on the instance, the "wildcard generic" is introduced, and for the above example, the wildcard generic format is used for < Extends Collection>, "? "Represents an unknown type, this type is implemented collection interface. Then the above-implemented way can be written as:

public static void Main (String args[]) {generics<arraylist> genlist = Null;genlist = new Generics<arraylist> ( New ArrayList ());//The following code can be compiled by GENERICS<? Extends collection> gencollention = null;gencollention=new generics<arraylist> (new ArrayList ()); System.out.println ("Can compile and run!");}

1. If only <?> is specified, and without extends, the default is to allow object and any Java classes below it. That is, any class.
2, wildcard generic type can not only limit downward, such as < Extends Collection>, can also limit upward, such as <? Super Double>, which indicates that a type can accept only Double and its upper-parent class type, such as number, an instance of type object.
3. Generic class definitions can have multiple generic parameters, separated by commas, and can also define generic interfaces, generic methods. These are similar to the usage rules for generics in generic classes.


Multi-Interface Restrictions
Although Java generics simply use extends to represent the original concept of extends and implements, but still adhere to the application of the system, Java can only inherit one class, but can implement multiple interfaces, so you need to use a certain type of extends qualification, And there are many types of time, there can only be one is a class, and the class is written in the first bit, the interface is listed in the following, that is: <t extends SomeClass & Interface1 & Interface2 & interface3>

The example here demonstrates only the type qualification of a generic method, with exactly the same rules for the restriction of type parameters in a generic class, just the header of the class declaration, such as:

public class Demo<t extends comparable & serializable>{//t types can be used comparable declarative methods and Seriablizable features}


Finally, it is emphasized that the most important function of generics is to improve the security of the code, because it is able to check the code at compile time, thus avoiding many exceptions that occur during the run-time strong-turn type. Understand the purpose of generics, and I believe you know how to use generics!


Beginners learn Java (22)--Re-understanding 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.