12.2简单泛型类的定义

2014-11-24 09:53:39 · 作者: · 浏览: 4

一个泛型类就是有一个或多个类型变量的类。
一般的类和方法,只能使用具体的类型(基本类型或者自定义类型)。如果要编译应用于多种类型的代码就要引入泛型了。
例12-1使用Pair类。静态方法minmax遍历数组同时计算出最小值和最大值。用一个Pair返回两个结果
[java]
package core.pair_12_1;


public class PairTest1 {

public static void main(String[] args) {
String[] words = {"Mary", "had", "a", "little", "lamb"};
Pair mm = ArrayAlg.minmax(words);
System.out.println("min = " + mm.getFirst());
System.out.println("max = " + mm.getSecond());
}
}

class ArrayAlg {

public static Pair 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(min, max);
}

}

class Pair {
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 getMiddle(T[] a) {
return a[a.length / 2];
}
注意,类型变量放在修饰符(这里是public static)后面,返回类型的前面。