/*
* 2018年3月27日09:30:50
* 代码目的:显示向容器中批量添加一组元素的方法。
* 代码位置:P220
* Collection<Integer> collection =
new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5));
这种方式也是最常用的。
结论:
Collections.addAll方法运行起来快。
因此先构建一个不包含元素的Collection,然后调用
Collections.addAll()这种方式很方便,因此是首选方式。
* */
//: holding/AddingGroups.java
// Adding groups of elements to Collection objects.
import java.util.*;
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方法的参数
//是一个容器
collection.addAll(Arrays.asList(moreInts));
System.out.println(collection);
// Runs significantly faster, but you can't
// construct a Collection this way:
//通过辅助类Collections.addAll向容器collection批量添加元素
Collections.addAll(collection, 11, 12, 13, 14, 15);
System.out.println(collection);
Collections.addAll(collection, moreInts);
// Produces a list "backed by" an array:
//注意:Arrays.asList会生成一个固定长度的链表list,可以通过set函数修改某个索引位置的值
//但如果尝试add或者remove会报错 java.lang.UnsupportedOperationException
List<Integer> list = Arrays.asList(16, 17, 18, 19, 20);
System.out.println(list);
list.set(1, 99); // OK -- modify an element
System.out.println(list);
//list.add(21); // Runtime error because the
// underlying array cannot be resized.
Collection<Integer> ii = new ArrayList<Integer>();
ii.addAll(Arrays.asList(16, 17, 18, 19, 20));
collection.addAll(ii);
System.out.println(collection);
}
} ///:~
/*
* --------------------------------
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
[16, 17, 18, 19, 20]
[16, 99, 18, 19, 20]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 6, 7, 8, 9, 10, 16, 17, 18, 19, 20]
* --------------------------------
* */