java ArrayList与LinkedList 使用for,forearch,Iterator的遍历效率



public class test {


/**
* @param args
*/
public static void main(String[] args) {
ArrayList<Integer> al=new ArrayList<Integer>();
   
for(int i=0;i<900000;i++){
al.add(new Integer(4));
}
showForForInter(al);
showFor(al);
showForEach(al);
showIterator(al);

}

//for int 循环遍历
public static void showForForInter(ArrayList<Integer> al){
int no=al.size();
long start =System.nanoTime();
for(int j=0;j<no;j++){
al.get(j);
}
long end =System.nanoTime();
System.out.println("for int 循环遍历:"+(end- start) / (1000));
}
//for循环遍历
public  static void showFor( ArrayList<Integer> al){
//开始编译执行时间
long start =System.nanoTime();

for(int j=0;j<al.size();j++){
al.get(j);
}
//执行完后的时间
long end =System.nanoTime();
System.out.println("for循环遍历:"+(end- start) / (1000));
}

//foEach循环遍历
public static void showForEach(ArrayList<Integer> al){
//开始编译执行时间
long start =System.nanoTime();
for(int j:al){
al.get(j);
}
//执行完后的时间
long end =System.nanoTime();
System.out.println("forEach循环遍历:"+(end- start) / (1000));
}

//Iterator遍历
public static void showIterator(ArrayList<Integer> al){
//开始编译执行时间
long start =System.nanoTime();
Iterator<Integer> it=al.iterator();
while(it.hasNext()){
it.next();
}
//执行完后的时间
long end =System.nanoTime();
System.out.println("Iterator循环遍历:"+(end- start) / (1000));
}
/*
* 9000条
for int 循环遍历:3038
for循环遍历:3658
forEach循环遍历:10548
Iterator循环遍历:4752*/

/*900000条
for int 循环遍历:9277
for循环遍历:11022
forEach循环遍历:38093
Iterator循环遍历:17727*/

}

将ArrayList<Integer>换成===>LinkedList<Integer>

9000条

for循环遍历:64875
forEach循环遍历:5897
Iterator循环遍历:2803

    

从上述来看,则是for循环更快些(先将list长度赋值,这样不用每次遍历都需要机选list长度,效率高了一点);

但是如果将测试的ArrayList替换成LinkedList,再来执行一遍相同的代码,将会得到惊讶的结果:for循环的效率实在是太低了,让人都没有耐心等程序执行完成了。

上种情况的出现for比iterator快,是因为对于ArrayList索引直接取值快,随机访问速度是ArrayList的优势所在。
综上所述,还是尽量提倡用iterator来遍历集合效果会更加好点。


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值