# 定義簡單泛型類

``````public 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;
}
}
``````

Pair類引入了一個類型變量T，用尖括號（<>）括起來，並放在類名的後面。泛型類可以有多個類型變量。例如，可以定義Pair類，其中第一個域和第二個域使用不同的類型。

``````public class Pair<T, U> {
...
}
``````

``````private T first;
``````

``````Pair<String>
``````

``````Pair<String>()
Pair<String>(String, String)
``````

``````String getFirst();
String getSecond();
void setFirst(String);
void setSecond(String);
``````

# 實例

## Pair.java

``````package cn.freedompc.pair;

public 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;
}
}
``````

## PairTest1.java

``````package cn.freedompc.pair;

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) {
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<>(min, max);
}
}

``````