Java Generic knowledge points

Source: Internet
Author: User

Java generics 1. Overview

generic : "Parameterized Type". The type is parameterized by the original concrete type, similar to the variable parameter in the method, when the type is also defined as a parameter form, and only the specific type is passed in at call/run time.

the nature of generics : In order to parameterize types, that is, in the case of not creating a new type, by reflecting on different types to control the type of formal parameter restrictions, that is, in the process of using generics, the data type of the operation is specified as a parameter, the modified type can be used in the generic class, the generic interface, The generic method.

2. Features

Generics are only valid at compile-time---> Because of generic type erasure of the JVM.

    List<String> l1 = new ArrayList<String>();    List<Integer> l2 = new ArrayList<Integer>();    /*输出结果为true*/    System.out.println(l1.getClass() == l2.getClass());

After verifying the type correctness of the generics during compilation, the relevant information is erased. That is, a generic type may appear to have many different types during the compilation phase, which is the same basic type in the post-compilation phase.

3. Use of generics
    • Generic class
    • Generic interface
    • Generic methods
3.1 Generic class

Through generics you can complete the operation of a set of classes to open the same interface, typically have a variety of container classes: List, Set, map and so on.

Basic notation for generic classes:

    class 类名 <泛型标识>{      /*该处T(泛型标识)由外部制定*/      private 泛型标识 成员变量名;      /**      *@param 自定义      *@return 返回泛型标识类型的类型       */      public 泛型标识 成员变量名(@param T t){}    }

Note
Generic identity: Can be written as arbitrary identity, common such as T, E, K, V.
When you instantiate a generic class, you must specify the specific type of T (including the custom Class), and you cannot make a simple type (such as int, double).

3.2 Generic interface

Generic interfaces are often used in a variety of class-based producers.

Basic syntax for generic interfaces:

    public interface 接口名<泛型标识/*这里用T*/>{      public T 方法名();    }    /**     *未传入泛型实参时,与泛型类的定义相同,在声明类的时候,需将泛型的声明也一起加到类中     *如不声明,编译器报错:"Unknown class"     */    class ImplGenerator<T> implements Generator<T>{      @override      public T next(){        return null;        }    }
3.3 Generic wild-letter wildcard

Such as:

    public void showKetValue(Geberic<?> obj){                Log.d("泛型测试","key value is " + obj.getKey());    }

Note :
Type wildcard characters are generally used instead of specific type arguments. As an integer, string, is an actual type.

usage Scenario : Can solve when the specific type is uncertain, this wildcard is?; When the operation type is not required to use the specific functionality of the type, it is only possible to use the function in the object class, then you can use the? wildcard character to represent an unknown type.

3.4 Generic methods

The member methods in most generic classes are also generic, and even some generic classes contain generic methods, which should be distinguished when learning.

Generic class: Indicates the specific type of the generic when instantiating the class; Generic method: Indicates the specific type of the generic when the method is called.
Generic methods can be used anywhere and in any scenario.

Basic notation for generic methods:

    /**     *@param t 传入泛型实参     *@return T 返回类型为T     *说明:     *1)只有声明了public和返回类型中间的<T>才是泛型方法     *2)<T>表示四该方法将使用的泛型类型为T,诸如T、E、K等,该T可出现在泛型方法任意位置     *3)Class<T>中的T表示为该类的泛型类型     *4)泛型的数量也可以为任意多个     *如:     *public <T,K> K showKeyName(Generic<T> container){...}     */         public <T> genericMethod(Class<T> t) throws InstantiationException,      IllegalAccessExceotion{        T instance = t.newInstance();        return instance;      }
3.4.1 generic method and variable function

Such as:

    public <T> void printMsg(T...args){      for(T t:args){        Log.d("Test"," t is " + t);      }    }
3.4.2 Static methods and generics

Static methods in a class use generics: static methods cannot access generics defined on a class, and when the reference data type of a method operation is undefined, the generic must be defined on that static method .

Such as:

    public class StaticGenerator<T> {    ....    /**     *如果在类中定义使用泛型的静态方法,需要添加额外的泛型声明(将这个方法定义成泛型方法)     *即使静态方法要使用泛型类中已经声明过的泛型也不可以。     *如:public static void show(T t){..},此时编译器会提示错误信息:          "StaticGenerator cannot be refrenced from static context"     */    public static <T> void show(T t){}    }
Summary of 3.4.3 Generic methods

Generic methods can be changed independently of the class, with the following basic principles:

Whenever possible, use a generic method if you can, that is, if you use a generic method to generics the entire class, you should use a generic method. Also, for a static method, you cannot access the parameters of a generic type. So if the important static method uses generic capabilities, it must be made a generic method.

4. The upper and lower bounds of a generic type
    • Add upper boundary, that is, the type argument passed in must be a specified parameter or its subtype
      public void showKeyValue(Generic<? extends Number> obj){}
    • Add the next boundary, that is, the incoming type argument must be a parameter or its parent
      public void showKeyValue(Generic<? super Integer> obj){}
    • Borderless, or wildcard?, see "3.3 Generic wildcard characters"

Example:

    //在泛型方法中添加上下边界限制的时候,必须在权限声明与返回值之间的<T>上添加上下边界,即在泛型声明的时候添加    //public <T> T showKeyName(Generic<T extends Number> container),编译器会报错:"Unexpected bound"    public <T extends Number> T showKeyName(Generic<T> container){      System.out.println("container key :" + container.getKey());      T test = container.getKey();      return test;    }

Note : The upper and lower bounds of a generic are added and must be declared together with the generic type

Java Generic knowledge points

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.