Java Basics "Generics"

Source: Internet
Author: User

I. Generic meaning: code written can be reused by different types of objects

Original mode: Use the object type and then make a strong turn;

Generic benefits: better security and readability;

Generic definition: A class that has one or more type variables;

Second, simple generic class example

1 /**generic class*/2 3 /*single Generic variable*/4  Public classPart1<t>{5 /*simple use of generics in methods*/6  PublicPart1 (T first,t second) {...}; 7 }8 9 /*Multiple Generic variables*/Ten  Public classPart2<t,u>{...}

Where: The scope of the type variable: Specifies the return type of the method, the domain ( Note!) ), the type of local variables;

The type variable represents the element type of the E-collection, the type of the keyword/value of the k/v-table, and T (which can be used when needed to represent "any type" in the adjacent u/s);

Iii. generic method (can be defined in a normal class)

Generic Method Example:

/** generic method Examples */ / * General class * / class arrayalg{/* type variable position: After modifier, return type before, where t ... Represents multiple generic parameters *    /publicstatic <T> getmiddle (T ... a)    {         return a[a.length/2];}    } // calling a generic method String middle = arrayalg.<string>getmiddle ("A", "B", "C");

IV. Qualification of type variables

(Here is the definition of the domain : field, a field is a property, can be a class variable, an object variable, an object method variable, or a function parameter.) (Supplemental, class ' s variables, instance variables and static variables of classes are called class ' s variables, generic variables, also known as class variables or data fields; Original: 38794007)

Java Basics "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.