泛型

泛型的出现使数据类型的错误止步在源码级别上,也就是我们所说的编译型错误。

今天就跟大家探讨下Java泛型以及自定义泛型的使用:

一、Java中的泛型

 

1 @Test
2
3 public void test()throws Exception{
4
5 //把List集合的类型限制在String类类型范围内,在这里使用了泛型
6  
7 List<String> list = new ArrayList<String>();
8
9 //向该集合中插入符合该泛型的数据
10  
11 list.add("a");
12
13 list.add("b");
14
15 list.add("c");
16
17 //迭代器迭代该泛型集合
18  
19 Iterator<String> it = list.iterator();
20
21 //输出该集合中的所有元素
22  
23 while(it.hasNext()){
24
25 String value = it.next();
26
27 System.out.println(value);
28
29 }
30
31 }
32
33
34
35 @Test
36
37 public void test02()throws Exception{
38
39 //键值泛型集合map
40  
41 Map<Integer, String> map = new HashMap<Integer, String>();
42
43 //向map集合中插入值
44  
45 map.put(1, "aa");
46
47 map.put(2, "bb");
48
49 map.put(3, "cc");
50
51 //使用set的集合来接受map中的对象
52
53 Set<Entry<Integer, String>> set = map.entrySet();
54
55 //使用JDK 1.5加强版循环来遍历map中的键以及所对应的值
56
57 for(Entry<Integer, String> entry:set){
58
59 System.out.println(entry.getKey()+"---"+entry.getValue());
60
61 }
62
63 }
64
65
66
67 @Test
68
69 public void test03()throws Exception{
70
71 //键值泛型集合map
72
73 Map<Integer, String> map = new HashMap<Integer, String>();
74
75 //向map集合中插入值
76
77 map.put(1, "aaa");
78
79 map.put(2, "bbb");
80
81 map.put(3, "ccc");
82
83 //使用set集合来接受map对象中的键
84
85 Set<Integer> set = map.keySet();
86
87 //同过JDK 1.5加强循环以及set中的键来获得对应的值
88
89 for(Integer value:set){
90
91 System.out.println(map.get(value));
92
93 }
94
95 }

//这种创建方式是错误的              List<String> list = new ArrayList<Object>();

//同上            List<Object> list1 = new ArrayList<String>();

              //以下创建时正确的,目的是为了统一jdk1.4  jdk1.5

              List<String> list = new ArrayList();

              List list1 = new ArrayList<String>();

二、自定义类的泛型使用

1 public class Demo02 {
2
3
4
5 //定义 泛型 在方法上定义
6
7 public <T> void test1(T l){ //应用的对象
8
9 }
10
11 public static <T> void test2(T l){ //应用的对象
12
13 }
14
15
16
17 public <T> int test3(T l){ //应用的对象
18
19 return 0;
20
21 }
22
23 public <T> List<T> test4(){
24
25 return null;
26
27 }

从以上的代码中我们可以看出泛型也可以定义使用在方法上,并且在泛型的<T>要放在方法的返回类型之前;

下面我们来看自定义泛型中的特殊情况:

1 public class Demo03<T,E> {
2
3
4
5 public void test1(T entity){
6
7
8
9 }
10
11
12
13 public List<T> test2(){
14
15 return null;
16
17 }
18
19
20
21 //在类上声明的泛型不能够用在static修饰的方法上
22
23 public static <TT> void test2(TT l){ //应用的对象
24
25
26
27 }
28
29 }

由上面的源码中可以看出泛型可以直接在类上直接声明,但在类上声明的泛型不能用在static修饰的方法上。

posted @ 2011-03-01 08:04  Laughing_Vzr@Stand By  阅读(605)  评论(0编辑  收藏  举报