1: package Test_Generics;
2:
3: import java.util.*;
4:
5: public class Test_CG {
6:
7: /**
8: * @param args
9: */
10: public static void main(String[] args) {
11: // TODO Auto-generated method stub
12:
13: /**泛型使用在集合上可限制傳入的物件型態*/
14: Vector<String> v1 = new Vector<String>();
15: v1.add("abc");
16: v1.add("def");
17: v1.add("ghi");
18: // v1.add(76);錯誤,只能放 String
19:
20: /**指定型別參數為 Integer*/
21: GenericA<Integer> gaI = new GenericA<Integer>();
22: gaI.setgaT(32);
23: // gaI.setgaT("123");錯誤 不可放入 String
24: System.out.println(gaI.getgaT());//32
25:
26: /**指定型別參數為 String*/
27: GenericA<String> gaS = new GenericA<String> ();
28: gaS.setgaT("abc123");
29: // gaS.setgaT(123);錯誤 不可放入int
30: System.out.println(gaS.getgaT());//abc123
31:
32: /**不指定型別參數*/
33: GenericA gb = new GenericA();
34: gb.setgaT(30.5);
35: System.out.println(gb.getgaT());//30.5
36:
37: /**使用泛型指定傳入參數,extends Integer 代表接受Integer及其子類別*/
38: testga1(new GenericA<String>());//null
39: // testga1(new GenericA<Integer>()); 錯誤,testga1方法指定只能接受String及其子類別
40:
41: /**使用泛型指定傳入參數,super Integer 代表接受Integer及其父類別*/
42: testga2(new GenericA<Number>());//123
43: }
44:
45: /**使用泛型指定傳入參數,extends Integer 代表接受Number及其子類別*/
46: static void testga1(GenericA<? extends String> gb)
47: {
48: System.out.println(gb.getgaT());
49: }
50:
51: /**使用泛型指定傳入參數,super Integer 代表接受Integer及其父類別*/
52: static void testga2(GenericA<? super Integer> ga)
53: {
54: ga.setgaT(123);
55: System.out.println(ga.getgaT());
56: }
57:
58: }
59:
60: //自訂泛型類別使用
61: class GenericA<T>//泛型記號 <T>
62: {
63: private int gaNum =0;
64: T gaT ;
65:
66: GenericA()
67: {
68: gaNum = 0;
69:
70: }
71:
72: GenericA(T tempt)
73: {
74: gaT = tempt;
75: }
76:
77: int getgaNum()
78: {
79: return gaNum;
80: }
81:
82: void setgaNum(int tempNum)
83: {
84: gaNum = tempNum;
85: }
86:
87: T getgaT()
88: {
89: return gaT;
90: }
91:
92: void setgaT(T tempt)
93: {
94: gaT = tempt;
95: }
96: }