12.2 definitions of simple generic classes

Source: Internet
Author: User

A generic class is a class with one or more type variables.
General classes and methods can only use specific types (basic type or custom type ). If you want to compile and apply code to multiple types, you need to introduce generics.
Example 12-1 uses the Pair class. The static method minmax traverses the array and calculates the minimum and maximum values simultaneously. Returns two results with one Pair.
[Java]
Package core. pair_12_1;
 
 
Public class PairTest1 {
 
Public static void main (String [] args ){
String [] words = {"Mary", "had", "a", "little", "lamb "};
Pair <String> mm = ArrayAlg. minmax (words );
System. out. println ("min =" + mm. getFirst ());
System. out. println ("max =" + mm. getSecond ());
}
}
 
Class ArrayAlg {
 
Public static Pair <String> minmax (String [] ){
// TODO Auto-generated method stub
If (a = null | a. length = 0)
Return null;

String min = a [0];
String max = a [0];

For (int I = 1; I <a. length; I ++ ){
If (min. compareTo (a [I])> 0)
Min = a [I];
If (max. compareTo (a [I]) <0)
Max = a [I];
}
Return new Pair <String> (min, max );
}

}
 
Class Pair <T> {
Private T first;
Private T second;
 
Public Pair (){
First = null;
Second = null;
}
Public Pair (T first, T second ){
This. first = first;
This. second = second;
}

Public T getFirst (){
Return first;
}
Public T getSecond (){
Return second;
}

Public void setFirst (T newValue ){
First = newValue;
}
Public void setSecond (T newValue ){
Second = newValue;
}
}


12.3 generic Method
Generic methods can be defined in generic classes or in common classes:
Public static <T> getMiddle (T [] ){
Return a [a. length/2];
}
Note that the type variable <T> is placed after the modifier (public static here) and before the return type.


 

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.