Java Generics overview

Source: Internet
Author: User

1. Why use generics

Generic classes and methods can only use specific types: either the base type or the custom class. If you want to write code that is appropriate for multiple types, the constraints on the code will be very large, so we need to use Java generics to solve this problem!

2. Generic terminology

Applicable to many many types

3. Targets for generics

It is mainly used to specify what type of object the container is to hold, and the editor guarantees the correctness of the type.

Therefore, instead of using object to express, it is better to use a temporary non-specified type, but later decide what type to use, that is, generics are recommended.

4. Concrete implementation

For this purpose, we need to use the type parameter, enclose it in angle brackets, and then place it behind the class name. Then, to use this class, replace the type parameter (T) with the actual type parameter.

Note: T is represented as a type parameter

Such as:

public class Base<t>{private T a;public Base (t a) {this.a=a}public void set (t a) {this.a=a}public T get () {return A;} public static void Main (string[] xx) {base<word> w=new base<word> (new Word); Word word = w.get ();..}}



Java Generics overview

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.