Java Foundation _ Custom Generics

Source: Internet
Author: User

Source of generics

In Java, generics are introduced by referencing the template functions of C + +.

    • C + + generics
intAddintXinty) {    returnX +y;}floatAddfloatX.floaty) {    returnX +y;}DoubleAddDoubleXDoubley) {    returnX +y;}//The abstract and implementation of the integer, floating-point number above the generic functiontemplate<classT>t Add (t x,t y) {returnX +y;}
    • Custom generics
 Public classMygeneric { Public Static voidMain (string[] args) {//general principles for generic inference to return the intersection in a generic parameter, and the generic parameter must be a reference type//3 Auto-boxing integer 5 auto-boxing integer so infer an integerInteger RESULT1 = Add (3, 5); //3.5 Auto-boxing Double 5 auto-boxing integer so infer common parent-class numberNumber RESULT2 = Add (3.5, 5); //3 Auto-boxing integer str1 String common intersection, all objectObject RESULT3 = Add (3, "str1")); }            /*** Definition of a generic method: * The angle brackets for the type parameter that is used to place the generic should appear after all other modifiers of the method and before the return type of the method, that is, immediately before the return value, the following <T> * By convention, type parameters are typically used with a single Uppercase letters indicate that * only reference types will be treated as parameters of the square method, and will automatically be boxed.@paramx *@paramy *@return     */     Public Static<T>t Add (t x,t y) {//here the compiler will error: the operator + is undefined for the argument type (s) T, T//because not all generics support + operations, but this method can see the Java type inference//T result = x + y;        return NULL; }}

Java Foundation _ Custom 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.