第20章學習有關Java SE5的註解java
第15章中,你將會了解到,使用Java泛型來建立類會很是複雜,可是,應用預約義的泛型一般會很簡單。app
ArrayList apples = new ArrayList();學習
apples.add(new Apple());ui
apples.add(new Orange());spa
ArrayList<Apple> apples = new ArrayList<Apple>();//使用了泛型,就能夠在編譯期防止將錯誤類型的對象放置到容器中。code
不能添加非Apple的對象。對象
可是能添加Apple的子類對象。blog
將在第17章瞭解更多有關散列碼的內容。io
全部的Collection均可以用foreach語法遍歷,本章後續學習「迭代器」。編譯
public class AddingGroups{ public static void main(String[] args){ Collection<Integer> collection = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5)); Integer[] moreInts = {6,7,8,9,10}; collection.addAll(Arrays.asList(moreInts)); Collection.addAll(collection, 11,12,13,14,15); Collection.addAll(collection, moreInts); List<Integer> list = Arrays.asList(16,17,18,19,20); list.set(1,99); //list.add(21); //Runtime error. } }
class Snow{} class Power extends Snow{} class Crusty extends Snow{} class Slush extends Snow{} class Light extends Power{} class Heavy extends Power{} public class AsListInference{ public static void main(String[] args){ List<Snow> snow1 = Arrays.asList(new Crusty(), new Slush(), new Power()); //Won't compile //List<Snow> snow2 = Arrays.asList(new Light(), new Heavy()); //Compiler says: //found: java.util.List<Power> //required:java.util.List<Snow> List<Snow> snow3 = new ArrayList<Snow>(); Collections.addAll(snow3, new Light(), new Heavy()); List<Snow> snow4 = Arrays.<Snow>asList(new Light(), new Heavy()); } }