Java Generics Summary

Source: Internet
Author: User
Tags uppercase letter

1. What is a generic type?

Generics (generics) are parameterized types, applied to classes, interfaces, methods, and can be assigned a type by executing a generic type call, replacing the generic type with the specific type of assignment. The assigned type will then be used to limit the values used within the container, eliminating the need for type conversions and providing a stronger type check at compile time.

2. What is the use of generics?

There are two main benefits of generics:

(1) Eliminate the forced type conversion of the display to improve code reuse

(2) Provide a stronger type check to avoid classcastexception at runtime

3, the use of generics

A type parameter, also known as a type variable, is used as a placeholder to indicate that the class is assigned a type at run time. Depending on your needs, you may have one or more type parameters and can be used for the entire class. By convention, a type parameter is a single uppercase letter that indicates the type of parameter that is defined. The standard type parameters for each use case are listed below:

E: Element

K: Key

N: Number

T: Type

V: Value

S, U, V, etc.: 2nd, 3, 4 types in multi-parameter cases

? Represents an indeterminate Java type (unrestricted wildcard type)

4. Bounded generics

<? Extends T>: refers to "upper bound wildcard (Upper Bounds wildcards)"

<? Super T>: means "nether wildcard (Lower Bounds wildcards)"

-There's a hole in here.

such as List<? Extends t> everyone thinks that the element is a list of the objects of T and all its subclasses. Not really. The element type refers to only one of the indeterminate subclasses of T, which is a single indeterminate class with no specific class. It is therefore not possible to insert an indeterminate.

list<? Super T> is a list of objects that everyone thinks is a T and its parent class. In fact, the element type only refers to an indeterminate parent class of T, which is a single indeterminate class (only the parent class of T is determined) and no specific class.

So:

Cannot go to list<? Inserts any type of object into the extends t>. The only guarantee is that you can read a subclass of T or T from it.

can go to list<? The super T> object that inserts T or T subclasses, but cannot insert the object of the T parent class. Objects that can be read to object (you don't know what subclasses are)

To summarize:

If you frequently support reading data, do not require write data, use <? Extends T>. That is, producers use <? Extends t>;

If you frequently support writing data, do not specifically require reading data, using < Super t>. That is, consumers use < Super t>;

If you need support, use <T>.

5. Type Erase

Java generics during compilation, all generic information will be erased.

    • Class C1 = new arraylist<integer> (). GetClass ();

      Class C2 = new arraylist<long> (). GetClass ();

      SYSTEM.OUT.PRINTLN (C1 = = C2);

      This is caused by the type erasure of the Java generics, because both arraylist<integer> and Arraylist<long> are erased by the compiler at compile time ArrayList. Java avoids the excessive consumption of runtime by creating a new class when creating a generic instance.

6. Generic type information

  • Well, if we do have certain scenarios, such as HTTP or RPC, or Jackson needs to get generics for serialization deserialization, you need to get generic type information.

    You can refer to the following:

  • ?
    1234567891011121314151617181920212223242526272829303132 //获取运行时的泛型类型信息public class Test2 {     static class ParameterizedTypeReference<T> {        protected final Type type;          public ParameterizedTypeReference() {            Type superClass = this.getClass().getGenericSuperclass();            //if (superClass instanceof Class) {    // throw new IllegalArgumentException(//"Internal error: TypeReference constructed without actual type information");            //  } else {                this.type = ((ParameterizedType) superClass).getActualTypeArguments()[0];            //}        }          public Type getType() {            return type;        }    }     public static void main(String[] args) {// System.out.println(new ParameterizedTypeReference<String>().getType());// java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType// 此处会输出报错,因此ParameterizedTypeReference 应不能直接实例化,可以考虑加abstract         System.out.println(new ParameterizedTypeReference<String>() { }.getType());// ParameterizedTypeReference 的匿名内部类,可以触发super(),//即 ParameterizedTypeReference()的构造器逻辑,正常运行    } }

      

  • Note A key point:

    You can get generic parameters at run time by defining the way the class is (usually an anonymous inner class, because we created the class just to get the generic information).

Java Generics Summary

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.