A brief analysis of generic type

Source: Internet
Author: User
Tags generator valid

The understanding of Java's generic features is limited to the shallow layer of the surface, until a detailed record is remembered until there is an understanding of the usage in the learning design pattern.

This article refers to Java Generics, generic methods in Java, and Java generics 1. Overview

Generics have a very important place in Java and are widely used in object-oriented programming and various design patterns.

What is a generic type. Why generics are used.

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 does the parameterized type understand it? 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. 2. A chestnut

An example that has been lifted countless times:

List arrayList = new ArrayList ();
Arraylist.add ("AAAA");
Arraylist.add (+);

for (int i = 0; i< arraylist.size (); i++) {
    String item = (string) arraylist.get (i);
    LOG.D ("Generic Test", "item =" + Item);
}
1 2 3 4 5 6 7 8

There is no doubt that the running result of the program ends with a crash:

Java.lang.ClassCastException:java.lang.Integer cannot is cast to java.lang.String
1

ArrayList can hold any type, the example adds a string type, adds an integer type, and then uses it as a string, so the program crashes. To solve problems like this (which can be solved at compile time), generics emerge.

We will change the code of the first line declaration to initialize the list, and the compiler will be able to help us find a problem like this in the compile phase.

list<string> arrayList = new arraylist<string> ();
...
Arraylist.add (100); In the compile phase, the compiler will error
1 2 3 3. Features

Generics are only valid during the compile phase. Look at the following code:

list<string> stringarraylist = new arraylist<string> ();
list<integer> integerarraylist = new arraylist<integer> ();

Class classstringarraylist = Stringarraylist.getclass ();
Class classintegerarraylist = Integerarraylist.getclass ();

if (Classstringarraylist.equals (classintegerarraylist)) {
    log.d ("Generic Test", "same type");
}
1 2 3 4 5 6 7 8 9

Output result: d/Generic Test: Same type.

The above example shows that the program will take a generic approach after compiling. This means that generics in Java are only valid during the compilation phase. When a generic result is correctly inspected during compilation, the information about the generic is erased and the method of type checking and type conversion is added at the boundary of the object's entry and exit methods. In other words, generic information does not go into the runtime phase.

This is summed up in a sentence: a generic type is logically viewed as multiple different types, and is actually the same basic type. 4. Use of generics

Generics are available in three ways: generic class, generic interface, generic method 4.3 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.

The most basic way of writing a generic class (This may seem a bit faint, as explained in the following example):

Class name < generic ID: Any identification number can be arbitrarily written, identifying the type of the specified generic >{
  private Generic identity/* (member Variable type) */var; 
  .....

  }
}
1 2 3 4 5 6

One of the most common generic classes:

Here t can be arbitrarily written as arbitrary identity, common parameters such as T, E, K, V, etc. are 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 this member variable is the T,T type 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;
    }
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14
A generic type parameter can only be a class type (including a custom class) and cannot be a simple type
//The argument type passed in is the same as the type parameter type of the generic, which is 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, which is string.
generic<string> genericstring = new Generic<string> ("Key_vlaue");
LOG.D ("Generic Test", "key is" + Genericinteger.getkey ());
LOG.D ("Generic Test", "key is" + Genericstring.getkey ());
1 2 3 4 5 6 7 8
12-27 09:20:04.432 13063-13063/? d/Generic test: Key is 123456
12-27 09:20:04.432 13063-13063/? d/Generic test: Key is Key_vlaue
1 2

Defined generic class, you must pass in the generic type argument. Not so, if you pass in a generic argument when you are using generics, you will have the appropriate restrictions based on the incoming generic arguments, at which point the generics will play a limiting role. If you do not pass in a generic type argument, a method or member variable in a generic class that uses a generic type can be of any type.

See an example:

Generic Generic = new Generic ("111111");
Generic Generic1 = new Generic (4444);
Generic generic2 = new Generic (55.55);
Generic generic3 = new Generic (false);

LOG.D ("Generic Test", "key is" + Generic.getkey ());
LOG.D ("Generic Test", "key is" + Generic1.getkey ());
LOG.D ("Generic Test", "key is" + Generic2.getkey ());
LOG.D ("Generic Test", "key is" + Generic3.getkey ());
1 2 3 4 5 6 7 8 9
d/Generic test: Key is 111111
d/Generic test: Key is 4444
d/Generic test: Key is 55.55
d/Generic test: Key is False
1 2 3 4

Note: 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.

if (ex_num instanceof generic<number>) {   
1 2 4.4 Generic interface

Generic interfaces are basically the same as the definition and use of generic classes. Generic interfaces are often used in a variety of classes of producers, you can see an example:

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

When a class that implements a generic interface does not pass in a generic argument:

/**
 * When a generic argument is not passed in, the definition of the generic class is the same, and when declaring the class, the generic declaration is added to the class as well
 : 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;
    }
}
1 2 3 4 5 6 7 8 9 10 11

When implementing a generic interface 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 

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.