对了,最近重新复习了ThinkinginJava(4th )。 顺便说一下,读完这么厚的书真的需要很大的勇气啊。
现在,看到拥有对象这一章,说的是Java中的集合类。 考虑到自己也使用了Java年以上,这些基础应该也很简单。 我刚看到第二行(' Collection.addAll ) )方法工作得快得多”这句话吸引了我。 之后,怀着要求验证的心情写了几个测试用例。
公共语音实用程序() {
用Arrays.asList方法初始化list,并将该list作为ArrayList的构造参数构建ArrayList
long a=System.nanoTime (;
collection collection=new ArrayList (arrays.as list (1,2,3,4,5 );
system.out.println('r
运行时为:'(system.nanotime(-a ) '纳秒');
a=System.nanoTime (;
Collection c=new ArrayList (;
c.Addall (arrays.as list (6,7,8,9,10 );
system.out.println('r
运行时为:'(system.nanotime(-a ) '纳秒');
a=System.nanoTime (;
Collection c2=new ArrayList (;
collections.addall (C2,11,12,13,14,15 );
system.out.println('r
运行时为:'(system.nanotime(-a ) '纳秒');
}
测试结果如下。
被测试的方法
测试次数
执行时间(纳秒)
平均(纳秒)。
新收集(收集收集) )。
1
32080
35159.2
2
35501
3
42773
4
30796
5
34646
Collection.addAll (
1
11121
11634.2
2
11121
3
14115
4
10693
5
11121
Collections.addAll (
1
19248
19846.6
2
18392
3
22670
4
19248
5
19675
结果直观,Collection.addAll ()方法速度最快,运行时间稳定。
因此,如果要为已知序列创建集合类的示例,请尽量使用Collection.addAll方法创建。
但是,Collections.addAll方法的参数更灵活,创建速度也更快。 也是比较好的选择。