1.容器类添加一组数据
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
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));
Collections.addAll(collection, 11, 12, 13, 14, 15);
Collections.addAll(collection, moreInts);
System.out.println("collection");
for(Integer i : collection)
System.out.print(i + ", ");
List<Integer> list = Arrays.asList(16, 17, 18, 19, 20);
list.set(1, 99); //modify an element
System.out.println();
System.out.println("list");
for(Integer i : list)
System.out.print(i + ", ");
//list.add(21); java.lang.UnsupportedOperationException--
Runtime error because the array cannot be resized.
}
}
collection.addAll()成员方法只能接受一个Collection对象作为参数,但是它不如Array.asList()或Collections.addAll()灵活,这两个方法使用的是可变参数列表。
j2se_1.6/api写道
Collection:
boolean addAll(Collection <? extends E > c)
Adds all of the elements in the specified collection to this collection (optional operation).
Arrays:
static <T> List<T> asList (T... a)
Returns a fixed-size list backed by the specified array.
Collections:
static <T> boolean addAll (Collection <? super T> c, T... elements)
Adds all of the specified elements to the specified collection.
boolean addAll(Collection <? extends E > c)
Adds all of the elements in the specified collection to this collection (optional operation).
Arrays:
static <T> List<T> asList (T... a)
Returns a fixed-size list backed by the specified array.
Collections:
static <T> boolean addAll (Collection <? super T> c, T... elements)
Adds all of the specified elements to the specified collection.