敲代码之泛型学习

1、一个简单的泛型案例

package test;

public class PairTest2 {
	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){
		if(a == null || a.length == 0) return null;
		String min = a[0];
		String max = a[0];
		for (int i = 0; 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;}
	
}

class Pair1 {
	private HS first;
	private HS second;
	
	public Pair1(){first = null; second = null;}
	public Pair1(HS first, HS second){this.first = first; this.second = second;}
	
	public HS getFirst(){return first;}
	public HS getSecond(){return second;}

	public void setFirst(HS newValue){first = newValue;}
	public void setSecond(HS newValue){second = newValue;}
	
}

说明:使用来声明一个类型持有者名称,然后就可以把T当作一个类型代表来声明成员、参数和返回值类型。


你可能感兴趣的:(Java)