码迷,mamicode.com
首页 > 编程语言 > 详细

Java面向对象程序设计--泛型编程

时间:2014-05-31 02:24:13      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

1. 为何要进行泛型编程?

泛型变成为不同类型集合提供相同的代码!省去了为不同类型而设计不同代码的麻烦!

 

2. 一个简单泛型类的定义:


bubuko.com,布布扣
 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 }
bubuko.com,布布扣

上面这段代码中定义了一个泛型类。

 

2. 泛型函数:

 

 




 

Java面向对象程序设计--泛型编程,布布扣,bubuko.com

Java面向对象程序设计--泛型编程

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/jiangheng/p/3761865.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!