2017.10.25 Java List /ArrayList 三种遍历方法

java list三种遍历方法性能比较

学习java语言list遍历的三种方法,顺便测试各种遍历方法的性能,测试方法为在ArrayList中插入记录,然后遍历ArrayList,测试代码如下:

package com.hisense.tiger.list;

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

public class ListTest {
	public static void main(String[] args)
	{
		List<String> list = new ArrayList<String>();
		long t1,t2;
		for(int j = 0; j < 10000000; j++)
		{
			list.add("aaaaaa" + j);
		}
		System.out.println("List first visit method:");
		t1=System.currentTimeMillis();
		for(String tmp:list)
		{
			//System.out.println(tmp);
		}
		t2=System.currentTimeMillis();
		System.out.println("Run Time:" + (t2 -t1) + "(ms)");
		System.out.println("List second visit method:");
		
		t1=System.currentTimeMillis();
		for(int i = 0; i < list.size(); i++)
		{
			list.get(i);
			//System.out.println(list.get(i));
		}
		t2=System.currentTimeMillis();
		System.out.println("Run Time:" + (t2 -t1) + "(ms)");
		
		System.out.println("List Third visit method:");
		Iterator<String> iter = list.iterator();
		
		t1=System.currentTimeMillis();
		while(iter.hasNext())
		{
			iter.next();
			//System.out.println(iter.next());
		}
		t2=System.currentTimeMillis();
		System.out.println("Run Time:" + (t2 -t1) + "(ms)");
				
		System.out.println("Finished!!!!!!!!");
		
		
	}
}

第一种:

   for(Iterator<A>    it    =    list.iterator();    it.hasNext();    )    {   

    it.next();
       ....   
   }   

第二种:

   for(A    a    :    list)    {   
       .....   
   }   

第三种:

   for(int    i=0;    i<list.size();    i++)    {   
       A    a    =    list.get(i);   
       ...   
   }   
``
posted @ 2017-10-25 22:05  LegendQi  阅读(172)  评论(0编辑  收藏  举报