T-and in Java generics?

Source: Internet
Author: User

Types are: simple types and complex types, and the introduction of generics has made the complex types more granular;

      • Now list, list is, 两种不同的类型 and 无继承 relationship;

      • The benefits of generics are as follows:

        Start version

        public void write(Integer i, Integer[] ia);public void write(Double d, Double[] da);

        Generic version

        public <T> void write(T t, T[] ta);

        Simple code.

Defining generics
        • 1. Define behind the class

          Follow the 类名 back.

          class TestClassDefine<T, S extends T>{}

          Defines generic t, S, and S inherits T

        • 2. Define after method 装饰符

          Immediately 修饰符 following (public)

          public <T, S extends T> T testGenericMethodDefine(T t, S s){}

          Defines generic t, S, and S inherits T

Instantiating generics
        • 1. 定义在类 Generics on instantiation

First statement 类变量 or 实例化时 . For example

    List<String> list; list = new ArrayList<String>;

Second 继承类 or 实现接口 time. For example

class MyList<E> extends ArrayList<E> implements List<E> {...} 
        • 2. 定义方法 Generics on instantiation

When the generic method is called, the compiler automatically assigns the value when the time is 类型参数(泛型) not successfully assigned to the Times compilation error

wildcard character (?)

The above has generics 定义 and 赋值 ; When in 赋值 , the above section says that the assignment is for 具体类型 , when the type 不确定 of assignment, we use 通配符(?) instead of:

Such as

 List<?> unknownList; List<? extends Number> unknownNumberList; List<? super Integer> unknownBaseLineIntgerList; 

In the Java Collection framework, for the container class where the parameter value is, 未知类型 只能 read the element, add the 不能 element to it,
Because the type is unknown, the compiler does not recognize that the type of the element being added and the type of the container is compatible, the only exception being null

T-and in Java 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.