1 import static java.lang.System.out; 2 3 import java.util.ArrayList; 4 import java.util.Collection; 5 import java.util.HashMap; 6 import java.util.HashSet; 7 import java.util.LinkedHashMap; 8 import java.util.LinkedHashSet; 9 import java.util.LinkedList; 10 import java.util.Map; 11 import java.util.TreeMap; 12 import java.util.TreeSet; 13 14 public class ContainerFramework { 15 16 static Collection fill(Collection<String> collection) { 17 collection.add("rat"); 18 collection.add("cat"); 19 collection.add("dog"); 20 collection.add("dog"); 21 return collection; 22 } 23 24 static Map fill(Map<String, String> map) { 25 map.put("rat", "Fuzzy"); 26 map.put("cat", "Rags"); 27 map.put("dog", "Bosco"); 28 map.put("dog", "Spot"); 29 return map; 30 } 31 public static void main(String[] args) { 32 out.println(fill(new ArrayList<String>())); 33 out.println(fill(new LinkedList<String>())); 34 out.println(fill(new HashSet<String>())); 35 out.println(fill(new TreeSet<String>())); 36 out.println(fill(new LinkedHashSet<String>())); 37 out.println(fill(new HashMap<String, String>())); 38 out.println(fill(new TreeMap<String, String>())); 39 out.println(fill(new LinkedHashMap<String, String>())); 40 } 41 }
上述代碼的運行結果為:
[rat, cat, dog, dog] [rat, cat, dog, dog] [cat, dog, rat] [cat, dog, rat] [rat, cat, dog] {cat=Rags, dog=Spot, rat=Fuzzy} {cat=Rags, dog=Spot, rat=Fuzzy} {rat=Fuzzy, cat=Rags, dog=Spot}
經過運行代碼,查看結果可以看出,Collection打印出來的內容用方括號[]括住,每個元素由逗號分隔;Map打印出來的內容用大括號{}括住,鍵與值用等號連接作為一個元素(鍵=值),每個元素用逗號分隔。
java容器類包括兩種:以Collection接口為根的集合類,和以Map為根的關聯數組類
2. Set有三個重要的實現,分別為HashSet,TreeSet,LinkedHashSet
3. Queue