1. 为何要进行泛型编程?
泛型变成为不同类型集合提供相同的代码!省去了为不同类型而设计不同代码的麻烦!
2. 一个简单泛型类的定义:
1 public class PairTest1
2 {
3 public static void main(String[] args)
4 {
5 String[] arr = {"This","is","the","end","of","the","world"};
6 Pair<String> mm = ArrayAlg.minmax(arr);
7 System.out.println("min = " + mm.getFirst());
8 System.out.println("max = " + mm.getSecond());
9 }
10 }
11
12 class Pair<T>
13 {
14 public Pair() {first = null; second = null;}
15 public Pair(T first,T second) {this.first = first; this.second = second;}
16
17 public T getFirst() {return first;}
18 public T getSecond() {return second;}
19
20 public void setFirst(T newValue) {this.first = newValue;}
21 public void setSecond(T newValue) {this.second = newValue;}
22
23 private T first;
24 private T second;
25 }
26
27 class ArrayAlg
28 {
29 public static Pair<String> minmax(String[] a)
30 {
31 if(a == null || a.length == 0) return null;
32 String min = a[0];
33 String max = a[0];
34 for(int i = 1; i < a.length; i++)
35 {
36 if(min.compareTo(a[i]) > 0) min = a[i];
37 if(max.compareTo(a[i]) < 0) max = a[i];
38 }
39 return new Pair<String>(min,max);
40 }
41 }
上面这段代码中定义了一个泛型类。
2. 泛型函数:
Java面向对象程序设计--泛型编程
时间: 2024-08-25 05:11:34