# 泛型方法

``````class ArrayAlg {
public static <T> T getMiddle(T... a) {
return a[a.length / 2];
}
}
``````

``````String middle = ArrayAlg.<String>getMiddle("John", "Q", "PUblic");
``````

``````String middle = ArrayAlg.getMiddle("John", "Q", "PUblic");
``````

``````double middle = ArrayAlg.getMiddle(3.14, 1729, 0);
``````

# 類型變量的限定

``````class ArrayAlg {
public static <T> T min(T[] a) {
if (a == null || a.length == 0) return null;
T smallest = a[0];
for (int i = 1; i < a.length; i++)
if (smallest.compareTo(a[i]) > 0) smallest = a[i];

return smallest;
}
}
``````

``````public static <T extends Comparable> T min(T[] a) ...
``````

``````<T extends BoundingType>
``````

``````T extends Comparable & Serializable
``````

# 實例

## PairTest2.java

``````package cn.freedompc.pair2;

import java.time.LocalDate;

import cn.freedompc.pair.Pair;

public class PairTest2 {

public static void main(String[] args) {
LocalDate[] birthdays = {
LocalDate.of(1906, 12, 9),
LocalDate.of(1815, 12, 10),
LocalDate.of(1903, 12, 3),
LocalDate.of(1910, 6, 22),
};
Pair<LocalDate> mm = ArrayAlg.minmax(birthdays);
System.out.println("min = " + mm.getFirst());
System.out.println("max = " + mm.getSecond());
}

}

class ArrayAlg {

public static <T extends Comparable> Pair<T> minmax(T[] a) {
if (a == null || a.length == 0) return null;
T min = a[0];
T 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<>(min, max);
}

}

``````