Java泛型和型別安全的容器

來源:互聯網
上載者:User

標籤:ges   app   指定   取值   樣本   orange   raw   type   swa   

樣本:

1 public class Apple {2     private static long counter;3     private final long id = counter++;4     5     public long id(){6         return id;7     }8 }
1 public class Orange {2 3 }
 1 public class ApplesAndOrangesWithoutGenerics { 2     @SuppressWarnings({ "rawtypes", "unchecked" }) 3     public static void main(String[] args) { 4         //定義一個ArrayList容器, 不指定其類型 5         ArrayList apples = new ArrayList(); 6         for (int i = 0; i < 3; i++) { 7             apples.add(new Apple()); 8         } 9         10         apples.add(new Orange());11         12         //此時, apples容器中存在4個對象, 其中前三個為Apple類型, 最後一個為Orange類型13         for (int i = 0; i < apples.size(); i++) {14             //get()方法取值時, 得到的只是Object的引用, 必須將其強制轉型為Apple, 否則編譯錯誤15             //當試圖將Orange對象轉型為Apple時, 發生類型轉換異常16             System.out.println(((Apple)apples.get(i)).id());17             /*18              * output:19              * 020              * 121              * 222              * */23         }24     }25 }

    在本例中,因為ArrayList儲存的是Object,所以可以將Apple對象和Orange對象放進容器中,當在使用ArrayList的get()方法來取出Apple對象時,得到的只是Object的引用,必須將其轉型為Apple,因此,需在調用Apple的id()方法之前,強制進行轉型,否則,

就會得到編譯錯誤。

 

    剛才聲明容器時沒有預先定義類型,預設為Object,現在使用預定義泛型來看看:

 1 public class ApplesAndOrangesWithoutGenerics2 { 2     public static void main(String[] args) { 3         //定義一個儲存Apple對象的ArrayList, 角括弧括起來的是型別參數 4         //它指定了這個容器樣本可以儲存的類型, 通過使用泛型, 就可以在編譯器放置將錯誤類型的對象放置到容器中 5         ArrayList<Apple> apples = new ArrayList<Apple>(); 6         for (int i = 0; i < 3; i++) { 7             apples.add(new Apple()); 8         } 9         10         //apples.add(new Orange());  編譯器可以阻止將Orange放置到apples中11         12         for (int i = 0; i < apples.size(); i++) {13             System.out.println(apples.get(i).id());14         }15         16         for (Apple c : apples) {17             System.out.println(c.id());18         }19         20         /*output21          * 022          * 123          * 224          * 025          * 126          * 227          * */28     }29 }

    我們注意到,定義了容器類型後,編譯器可以阻止將Orange放置到apples中,因為此時Orange對象的類型與容器類型不符,發生編譯錯誤;另外,將元素從容器中取出時,類型轉換也不再時必須的了,因為容器知道自己儲存的是什麼類型,因此會在調用

get()時幫忙轉型。

Java泛型和型別安全的容器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.