Java generic methods and type qualification

Source: Internet
Author: User
Tags comparable

generic methods can be defined in a normal class or in a generic class
1 class arrayalg{2      Public static <T> T getmiddle (t...a) {3         return a[a.length/2]; 4     }5 }

Note: Type variables are placed after modifiers (public static)when a generic method is called, the method name is placed in a specific type before the angle brackets
String middle=arrayalg.<string>getmiddle ("John", "Q.", "public");

in most cases, the method call can omit the <String> type parameter
String middle=arrayalg.getmiddle ("John", "Q.", "public");

qualification of type variablessometimes a class or method needs to constrain a type variable
1 classarrayalg{2      Public Static<T>T min (t[] a) {3         if(a==NULL|| a.length==0)return0;4T smallest=a[0];5          for(inti=1;i<a.length;i++)6             if(Smallest.compareto (A[i]) >0)7smallest=A[i];8             returnsmallest;9     }Ten}

in the example above, the variable smallest type is T, and the smallest must have a CompareTo method to run properlythe workaround is to limit t implementation of the comparable interface
 Public Static extends comparable> T min (t[] a) ...

a type variable or wildcard can have more than one qualification, with a qualified type of & delimited
extends Comparable & Serializable

Java generic methods and type qualification

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.