Java中泛型使用

來源:互聯網
上載者:User

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>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.