<CoreJava> 12.4类型变量的定义
有时类或方法需要对类型变量加以约束。
- 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;
- }
- }
问题:min方法内部的变量smallest类型为T,意味着它可以是任意类的对象。那么如何确定T所属的类有compareTo方法呢?
解答:将T限制为实现Comparable接口的类。通过对类型变量T设置限定实现这一点:public static <T extends Comparable> T min(T[] a).......
注意:一个类型变量或通配符可以有多个限定:T extends Comparable & Serializable(限定类型用&分隔,类型变量用,分隔)
例12-2中重新编写了一个泛型方法minmax。方法是计算数组中的最大值和最小值并返回Pair<T>
- package core.pair_12_2;
- import java.util.Calendar;
- import java.util.GregorianCalendar;
- /**
- * @author vincent
- */
- public class PairTest2 {
- public static void main(String[] args) {
- GregorianCalendar[] birthdays =
- {
- new GregorianCalendar(1906, Calendar.DECEMBER, 9),
- new GregorianCalendar(1815, Calendar.DECEMBER, 10),
- new GregorianCalendar(1903, Calendar.DECEMBER, 3),
- new GregorianCalendar(1910, Calendar.JUNE, 22),
- };
- Pair<GregorianCalendar> mm = ArrayAlg.minmax(birthdays);
- System.out.println("min = " + mm.getFirst().getTime());
- System.out.println("max = " + mm.getSecond().getTime());
- }
- }
- class ArrayAlg {
- @SuppressWarnings({ "rawtypes", "unchecked" })
- 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<T>(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;
- }
- }