Java中 List的遍历及三种遍历方法

Java List遍历方法 及其效率对比


package com.zbalpha.test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ListTest {undefined
    public static void main(String args[]){undefined
        List<Long> lists = new ArrayList<Long>();

        for(Long i=0l;i<1000000l;i++){undefined
            lists.add(i);
        }  
        
        Long oneOk = oneMethod(lists);
        Long twoOk = twoMethod(lists);
        Long threeOk = threeMethod(lists);
        Long fourOk = fourMethod(lists);
        
        System.out.println("One:" + oneOk);
        System.out.println("Two:" + twoOk);
        System.out.println("Three:" + threeOk);
        System.out.println("four:" + fourOk);
        
    }
    
    public static Long oneMethod(List<Long> lists){undefined
        
        Long timeStart = System.currentTimeMillis();
        for(int i=0;i<lists.size();i++)    {undefined
            System.out.println(lists.get(i));
        }
        Long timeStop = System.currentTimeMillis();

        return timeStop -timeStart ;
    }
    
    public static Long twoMethod(List<Long> lists){undefined
        
        Long timeStart = System.currentTimeMillis();
        for(Long string : lists)    {undefined
            System.out.println(string);
        }
        Long timeStop = System.currentTimeMillis();

        return timeStop -timeStart ;
    }
    
    public static Long threeMethod(List<Long> lists){undefined
        
        Long timeStart = System.currentTimeMillis();
        Iterator<Long> it = lists.iterator();
        while (it.hasNext())
        {undefined
                System.out.println(it.next());
        }
        Long timeStop = System.currentTimeMillis();

        return timeStop -timeStart ;
    }    
    
       
    public static Long fourMethod(List<Long> lists){undefined
        
        Long timeStart = System.currentTimeMillis();
        for(Iterator<Long> i = lists.iterator(); i.hasNext();)    {undefined
            System.out.println(i.next());
        }
        Long timeStop = System.currentTimeMillis();

        return timeStop -timeStart ;
    }    
}

容器类可以大大提高编程效率和编程能力,在Java2中,所有的容器都由SUN公司的Joshua Bloch进行了重新设计,丰富了容器类库的功能。 

  Java2容器类类库的用途是“保存对象”,它分为两类: 

  Collection----一组独立的元素,通常这些元素都服从某种规则。List必须保持元素特定的顺序,而Set不能有重复元素。 

  Map----一组成对的“键值对”对象,即其元素是成对的对象,最典型的应用就是数据字典,并且还有其它广泛的应用。另外,Map可以返回其所有键组成的Set和其所有值组成的Collection,或其键值对组成的Set,并且还可以像数组一样扩展多维Map,只要让Map中键值对的每个“值”是一个Map即可。 

。。。。。。。。。。。。。。。。。

版权原因,完整文章,请参考如下:Java中 List的遍历及三种遍历方法

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值