Java中泛型使用
泛型: 1.5 之後出現 提高安全 1 泛型 確定 集合容器的類型。 2 <> 接收一種資料類型,(引用資料類型) ArrayList lis = new ArrayList() 目的: 將運行時期的 錯誤 轉化到 編譯時間期,提高了安全性! 3 不需要 強制類型轉換. 更加安全!
泛型的 擦除: 泛型在編譯時間期使用!使用完畢直接擦除。 編譯完的時候 不存在 泛型。
好處: 使用了 泛型,不自需要強制類型轉換?(多種資料類型) 為什麼? 因為容器中只有一種資料類型。 取出資料之後,在處理資料細節!String 就是 很重要的。在現實的開發中。
泛型自訂的類:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14 |
//使用泛型
class Tools<t>
{
private T obj;
public void setObject(T obj)
{
this.obj = obj;
}
public T getObject()
{
return this.obj;
}
}</t>
|
泛型應用在方法上:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31 |
class Test<e>
{
//泛型用在方法上
//當類中的某個方法所使用的類型只有在類上的類型確定了才能確定時,就在方法上使用
//泛型
//否則不用泛型
public void func(E e)
{
System.out.println(e);
}
//該方法單獨使用泛型: 方法使用的類型不確定,而且什麼類型都行
//這個 方法被調用時,類型才確定
public <t> void show(T e)
{
System.out.println(e);
}
//靜態是隨著類的載入而載入,這是不存在類型,所以靜態方法只能自己定義泛型
public static <w> void function(W e)//Test.function()
{
System.out.println(e);
}
public void ff(int a,int b)
{
System.out.println(a+b);
}
}</w></t></e>
|
泛型 定義在介面上:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 |
//泛型用在介面上
interface inter<t>
{
public void show(T t);
}
class Test implements inter<string>
{
public void show(String t)
{
}
}
class Demo<e> implements inter<e>
{
public void show(E t)
{
System.out.println(t);
}
}
class Demo9
{
public static void main(String[] args)
{
Demo<string> d = new Demo<string>();
d.show(99);// error
}
}
</string></string></e></e></string></t>
|