java容器主要分为两类:
1)Collection, 一个独立元素的序列,此类容器主要包括List(以特定顺序保存一组元素)、Set(元素不重复)和Queue(只允许元素从一端插入,另一端移除,先进先出)
2) Map,一组成对的键值对,允许根据键值查找。
添加容器元素
1) 使用Arrays.asList(),将一组数据转成ArrayList, 并赋值给collection
2) 使用collection.addAll 将一组元素添加到集合中
3)使用工具类Collections.addAll(Collection c, ... elements), 将元素添加到集合中
public static void main(String[] args){
Collection<Integer> collection = new ArrayList<>(Arrays.asList(1,2,3,4,5));
Integer[] moreInts = {6,7,8,9,10}; // 初始化数组,使用大括号
collection.addAll(Arrays.asList(moreInts));
System.out.println("collection: " + collection);
// use Collections 工具类
Collections.addAll(collection,11,12,13,14,15);
Collections.addAll(collection, moreInts);
System.out.println("collection: " + collection);
}
程序输出(允许有重复元素):
collection: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
collection: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 6, 7, 8, 9, 10]
注意: Arrays.asList()的输出是一个数组,长度固定,不能调整尺寸,使用add or delete 会报错。
打印容器元素
static Collection fill(Collection<String> collection){
collection.addAll(Arrays.asList("rat","cat","dog","pig"));
return collection;
}
static Map fill(Map<String,String> map){
map.put("rat", "Fuzzy");
map.put("cat", "Kat");
map.put("dog", "Mosco");
return map;
}
public static void main(String[] args){
System.out.println(fill(new ArrayList<>()));
System.out.println(fill(new LinkedList<>()));
System.out.println(fill(new HashSet<>()));
System.out.println(fill(new TreeSet<>()));
System.out.println(fill(new HashMap<>()));
System.out.println(fill(new TreeMap<>()));
}
程序输出:
[rat, cat, dog, pig]
[rat, cat, dog, pig]
[rat, cat, dog, pig]
[cat, dog, pig, rat]
{rat=Fuzzy, cat=Kat, dog=Mosco}
{cat=Kat, dog=Mosco, rat=Fuzzy}
默认的打印行为,可读性很好,他使用了容器提供的toString 方法。Collection 打印出的元素用中括号,元素之间以逗号分隔;Map打印出的元素以大括号,等号左边是key,右边是value,各元素之间以逗号分隔。
容器关系概要图
注意:下图仅用来概要描述容器之间的依赖关系,并不完全表示类之间的关系。