泛型總結 day11

---------------------- android培訓java培訓、期待與您交流! ----------------------

雨一直下,對泛型的總結,強制自己複習:

 

泛型概述?
JDK1.5版本以後出現的新特性。用於解決安全問題,是一個安全機制。

好處:
1.將運行時期出現的問題 ClassCastException ,轉移到了編譯時期,
 方便程序員解決問題。讓運行時期問題減少,安全
2.避免了強制轉換麻煩。

泛型格式:
通過<>來定義操作的引用數據類型

在使用java提供的對象時,什麼時候使用泛型呢?

通常情況下,在集合框架中很常見,只要見到<>就要定義泛型
其實<>就是用來接收類型的(這個類型是引用數據類型),當使用集合時,將集合中要存儲的數據類型作爲參數傳遞到<>中即可,
與函數傳參數類似。

什麼時候定義泛型?
當類中要操作的“引用數據類型”不確定的時候,早期定義 Object 來完成擴展,現在定義泛型來擴展
注意泛型只針對引用數據類型,基本數據類型不行。


泛型類?
泛型類定義的泛型,在整個類中有效,如果被方法使用,
那麼泛型類的對象明確要操作的具體類型後,所有要操作的類型都已經固定了
class Demo<T>
{
 public void show(T t)
 {
  System.out.println("show:"+t);
 }

 public void print(T t)
 {
  System.out.println("print:"+t);
 }
}

class  GenericDemo4
{
 public static void main(String[] args)
 {
  Demo<String> d=new Demo<String>();

  d.show("javal01");
  d.print("adlja");
 }
}

爲了讓不同方法可以操作不同類型,而且類型還不確定,可以將泛型定義在方法上。

class Demo
{
 public <T> void show(T t)
 {
  System.out.println("show:"+t);
 }
 public <Q> void print(Q q)
 {
  System.out.println("print:"+q);
 }
}

class  GenericDemo4
{
 public static void main(String[] args)
 {
  Demo d=new Demo();

  d.show("javal01");
  d.print(123);
  d.show(123);
  d.print("adljfa")
 }
}

集合的泛型就是定義在類上,對象類型已明確,所有的操作方法都是這個類型

泛型既可以定義在類上,又可以定義在方法上,
特殊之處:靜態不可以訪問類上定義的泛型,因爲T是對象類型,靜態先加載,即靜態不能操作非靜態
如果靜態方法操作的應用數據類型不確定,可以將泛型定義在方法上。

用泛型,但不能利用類型特有方法


class Demo<T>
{
 public void show(T t)
 {
  System.out.println("show:"+t);
 }
 public <Q> void print(Q q)
 {
  System.out.println("print:"+q);
 }

 public static <T> void method(T t)
 {
  System.out.println("method"+t);
 }
}

class  GenericDemo4
{
 public static void main(String[] args)
 {
  Demo<String> d=new Demo<String>();

  d.show("javal01"); //只能操作String類型
  d.print(123);
  d.print("adljfa")
 }
}


泛型定義在接口上

interface Inter<T>
{
 void show(T t);
}

class InterImpl implements Inter<String>
{
 public void show(String t)
 {
  System.out.println("show:"+t);
 }
}

class  GenericDemo5
{
 public static void main(String[] args)
 {
  InterImpl i=new InterImpl();
  i.show("jajs");
  System.out.println("Hello World!");
 }
}

如果實現接口過後還不能確定操作類型


interface Inter<T>
{
 void show(T t);
}

class InterImpl<T> implements Inter<T>
{
 public void show(T t)
 {
  System.out.println("show:"+t);
 }
 public <T> void print(T t)
 {
  System.out.println("print:"+t);
 }
}
class  GenericDemo5
{
 public static void main(String[] args)
 {
  InterImpl<String> i=new InterImpl<String>();
  i.show("jajs");
  i.print(123);
  System.out.println("Hello World!");
 }
}


通配符,也可以理解爲佔位符。

泛型的限定:
? extends E:可以接收E類型或者E的子類型 ,上限
? super E:可以接收E類型,或者E的父類型 ,下限

泛型限定是用來進行泛型擴展用的,有擴展性就有侷限性,只能調用父類的方法。

 

今天就到這吧


---------------------- android培訓java培訓、期待與您交流! ----------------------詳細請查看:http://edu.csdn.net/heima 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章