今天看见网上有个List 遍历方式讨论贴见 http://pda158.iteye.com/blog/2158898
第一种方式遍历每次会生成句柄 所以比较慢,改进版代码如下:
  
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 < 800000; j++)  {  
			list.add("aaaaaa" + j);  
		}  
	System.out.println("List first visit method:");  
	
//	t1=System.currentTimeMillis();  
//	for(String tmp:list)  {  
////		tmp;
//	}  
//	t2=System.currentTimeMillis();  
//	System.out.println("List first visit Run Time:" + (t2 -t1) + "(ms)");  
//	
//	System.out.println("List second visit method:");  
//	t1=System.currentTimeMillis();  
//	for(int i = 0; i < list.size(); i++)  {  
//		String tmp = list.get(i);
//	}  
//	t2=System.currentTimeMillis();  
//	System.out.println("List second visit Run Time:" + (t2 -t1) + "(ms)");  
//	
	System.out.println("List Third visit method:");  
	Iterator<String> iter = list.iterator();  
	t1=System.currentTimeMillis();  
	while(iter.
hasNext())  {  
		String tmp =iter.next();  
	}  
	t2=System.currentTimeMillis();  
	System.out.println(" List Third visit Run Time:" + (t2 -t1) + "(ms)");  
	System.out.println("Finished!!!!!!!!");  
	}  
}  
结果:
List first visit Run Time:35(ms)
List second visit Run Time:21(ms)
 List Third visit Run Time:35(ms)
1 同样第二种方式快,因为它直接从List中取出数据
2 1,3方式差不多
解释:
1,3 方式,所以时间是差不多的
 Java 中的 foreach 语法是 iterator(迭代器)的变形用法
 for (Iterator<Integer> i = list.iterator(); i.hasNext();) {  
1,2 方式比较
 public E next() {  
        checkForComodification();  
        try {  
            E next = get(cursor);  
            lastRet = cursor++;  
            return next;  
        } catch (IndexOutOfBoundsException e) {  
            checkForComodification();  
            throw new NoSuchElementException();  
        }  
    }  
    在迭代器的  next() 方法中也出现了下标访问方式没有的 checkForComodification() 方法和 lastRet 变量赋值操作。这也就是通过 foreach 方式遍历耗时的原因。