记录
Thinking in java p220
import java.util.*;
public class classtest {
public static void main(String[] args) {
//用List初始化
Collection<Integer> collection = new ArrayList<Integer>
(Arrays.asList(1, 2, 3, 4, 5));
//Collections.addAll(Collections,Array/用逗号隔开的列表)
Integer[] temp1 = {6,7,8,9,10};
Collections.addAll(collection,temp1);
Collections.addAll(collection,11,12,13,14,15);
//collection(变量名).addAll(List)
Integer[] temp2 = {16,17,18,19,20};
collection.addAll(Arrays.asList(temp2));
System.out.println(collection);
/*
结果显示:*[1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25]*
(没有换行)
*/
}
}
Collection的构造器可以接受另一个Collection作为参数来初始化,所以可以用Arrays.asList()将数组转化为Collection中的List中的ArrayList来初始化。
long startTime,endTime;
System.out.print("用 Collection作为参数初始化Collection ");
startTime=System.nanoTime();
Collection<Integer> collection1 =
new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5));
endTime=System.nanoTime();
System.out.println("运行时间: "+(endTime-startTime)+"ns");
/*
结果显示:*用 Collection作为参数初始化Collection 运行时间: 33600ns*
*/
让我们尝试用addAll方法接受 数组转化为List 添加元素。
System.out.print("用 addAll方法接受 数组转化为的List 添加元素 ");
startTime=System.nanoTime();
Collection<Integer> collection2 = new ArrayList<Integer>();
collection2.addAll(Arrays.asList(1, 2, 3, 4, 5));
endTime=System.nanoTime();
System.out.println("运行时间: "+(endTime-startTime)+"ns");
/*
用 addAll方法接受 数组转化为的List 添加元素 运行时间: 11600ns*
*/
再尝试用Collections中的方法addAll接受Collection和用逗号隔开的列表。
System.out.print("用 Collections方法addAll接受Collection和用逗号隔开的列表 ");
startTime=System.nanoTime();
Collection<Integer> collection3 = new ArrayList<Integer>();
Collections.addAll(collection3, 1, 2, 3, 4, 5);
endTime=System.nanoTime();
System.out.println("运行时间: "+(endTime-startTime)+"ns");
/*
结果显示:*用 Collections方法addAll接受Collection和用逗号隔开的列表
运行时间: 33200ns*(没有换行)
*/
最后用 Collections方法addAll接受Collection和数组。
System.out.print("用 Collections方法addAll接受Collection和数组");
startTime=System.nanoTime();
Collection<Integer> collection4 = new ArrayList<Integer>();
Integer[] a ={1,2,3,4,5};
Collections.addAll(collection4, a);
endTime=System.nanoTime();
System.out.println("运行时间: "+(endTime-startTime)+"ns");
/*
结果显示:*用 Collections方法addAll接受Collection和数组运行时间: 3900ns*
*/
可见,最后的 用 Collections方法addAll接受Collection和数组 的方法是最为快速的,所以我们将这种方法列为首选。