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.