Posted on 2009-07-07 13:53
WANGPENG 阅读(159)
评论(0) 编辑 收藏 所属分类:
Java
泛型(Generics)
1 package com.ztejc.wp ;
2
3 public class GenericFoo<T> {
4 private T foo ;
5
6 public void setFoo(T foo) {
7 this.foo = foo ;
8 }
9
10 public T getFoo() {
11 return this.foo ;
12 }
13
14 public static void main(String[] args) {
15 GenericFoo<Boolean> booleanFoo = new GenericFoo<Boolean>() ;
16 booleanFoo.setFoo(new Boolean(true)) ;
17 System.out.println(booleanFoo.getFoo()) ;
18 }
19 }
1 package com.ztejc.wp ;
2
3 public class GenericFooArray<T> {
4 private T[] foo ;
5
6 public void setFoo(T[] foo) {
7 this.foo = foo ;
8 }
9
10 public T[] getFoo() {
11 return this.foo ;
12 }
13
14 public static void main(String[] args) {
15 String[] sArray1 = {"hello" , "world"} ;
16 String[] sArray2 = null ;
17
18 GenericFooArray<String> stringFoo = new GenericFooArray<String>() ;
19 stringFoo.setFoo(sArray1) ;
20 sArray2 = stringFoo.getFoo() ;
21
22 for (int i=0 ; i<sArray2.length ; i++) {
23 System.out.println(sArray2[i]) ;
24 }
25 }
26 }
27
1 package com.ztejc.wp ;
2
3 @SuppressWarnings("unchecked")
4 public class GenericFooSimpleCollection<T> {
5 private T[] objArr ;
6
7 private int index = 0 ;
8
9 public GenericFooSimpleCollection() {
10 objArr = (T[]) new Object[10] ;
11 }
12
13 public GenericFooSimpleCollection(int c) {
14 objArr = (T[]) new Object[c] ;
15 }
16
17 public void add(T t) {
18 objArr[index] = t ;
19 index++ ;
20 }
21
22 public T get(int i) {
23 return objArr[i] ;
24 }
25
26 public int getLength() {
27 return index ;
28 }
29
30 public static void main(String[] args) {
31 GenericFooSimpleCollection<Integer> g = new GenericFooSimpleCollection<Integer>() ;
32
33 for (int i = 0 ; i < 10 ; i++ ) {
34 g.add(new Integer(i)) ;
35 }
36
37 for (int i = 0 ; i < 10 ; i++ ) {
38 Integer k = g.get(i) ;
39 System.out.println(k) ;
40 }
41 }
42 }
43
如果对泛型的类型需要约束的时候就用继承某个类或实现某个接口对其进行约束,当没有指明限制为何种类型的时候,默认使用的是T extends Object.所以能够传入任何类型的数据类型.
注意:在泛型的使用中,继承某个类或实现某个接口对其进行限制时,一律使用关键字extends.不能使用implements,这是错误的语法.
1 package com.ztejc.wp ;
2
3 import java.util.ArrayList ;
4 import java.util.LinkedList ;
5 import java.util.List ;
6
7 public class ListGenericFoo<T extends List> {
8 private T foo ;
9
10 public void setFoo(T t) {
11 this.foo = t ;
12 }
13
14 public T getFoo() {
15 return this.foo ;
16 }
17
18 public static void main(String[] args) {
19 ListGenericFoo<ArrayList> foo1 = new ListGenericFoo<ArrayList>() ;
20 ListGenericFoo<LinkedList> foo2 = new ListGenericFoo<LinkedList>() ;
21
22 ArrayList arrList = new ArrayList() ;
23 LinkedList linList = new LinkedList() ;
24
25 foo1.setFoo(arrList) ;
26 foo2.setFoo(linList) ;
27 }
28 }
使用?进行类型统配声明
1 GenericFoo<? extends List> foo = null ;
2 foo = new GenericFoo<ArrayList>() ;
3 foo = new GenericFoo<LinkedList>() ;
如果使用泛型,只要在编译期间没有出现警告,就不会遇到运行时ClassCastException.
增强的"for"循环(Enhanced For Loop)
自动置入/自动取出(Autoboxing/Unboxing)
类型安全的枚举(Type safe enums)
静态导入(Static import)
可变参数(Var args)