---
title: "12.2简单泛型类的定义"
author: "poyunri"
date: "2012-10-22T10:34:00Z"
tags: []
slug: "12-2"
draft: false
lastmod: "2012-12-20T18:21:17Z"
id: 1751256
url: "https://poyunri.iteye.com/blog/1751256"
---

一个泛型类就是有一个或多个类型变量的类。

一般的类和方法，只能使用具体的类型（基本类型或者自定义类型）。如果要编译应用于多种类型的代码就要引入泛型了。

例12-1使用Pair类。静态方法minmax遍历数组同时计算出最小值和最大值。用一个Pair返回两个结果

```
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[] a) {
        // 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泛型方法

泛型方法可以定义在泛型类中也可以定义在普通类中：

public static &lt;T&gt; getMiddle(T\[] a) {

return a\[a.length / 2];

}

注意，类型变量&lt;T&gt;放在修饰符（这里是public static）后面，返回类型的前面。