码迷,mamicode.com
首页 > 其他好文 > 详细

用for和while遍历HashMap效率测试

时间:2014-08-15 10:47:58      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:java   hashmap   遍历   iterator   

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;

public class EntryTest {
	public static void main(String[]  args) {
		
		Map<Integer, String> map = new HashMap<Integer, String>();
		for (int i = 0; i <= 6000000; i++) {
			map.put(i, "a" + i);
		}
		
		//使用while和entrySet遍历HashMap
		long startTime1 = Calendar.getInstance().getTimeInMillis();		
		Iterator iterator = map.entrySet().iterator();
		while(iterator.hasNext()) {
			Map.Entry<Integer, String> entry = (Map.Entry<Integer, String>)iterator.next();
			entry.getKey();
			entry.getValue();
			//System.out.println(entry.getKey() + ": " + entry.getValue());
		}
		long endTime1 = Calendar.getInstance().getTimeInMillis();
		
		//输出方法1的耗时
		System.out.println("costTime1 = " + (endTime1-startTime1));
		
		//使用for和entrySet遍历
		long startTime2 = Calendar.getInstance().getTimeInMillis();
		for (Map.Entry<Integer, String> entry:map.entrySet()) {
			entry.getKey();
			entry.getValue();
			//System.out.println(entry.getKey() + ": " + entry.getValue());
		}
		long endTime2 = Calendar.getInstance().getTimeInMillis();
		
		//输出方法2的耗时
		System.out.println("costTime2 = " + (endTime2-startTime2));		
	}
	
}
结果输出:
costTime1 = 96
costTime2 = 89

用for和while遍历HashMap效率测试,布布扣,bubuko.com

用for和while遍历HashMap效率测试

标签:java   hashmap   遍历   iterator   

原文地址:http://blog.csdn.net/u011402596/article/details/38580577

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!