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

HashMap的keySet遍历和entrySet遍历时间效率比较

时间:2014-08-14 20:47:59      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:java   遍历   keyset   entryset   

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


public class HashMapTest {
<span style="white-space:pre">	</span>public static void main(String[] args) {
<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>Map<Integer, String> map = new HashMap<Integer, String>();
<span style="white-space:pre">		</span>for (int i = 0; i <= 5000000; i++) {
<span style="white-space:pre">			</span>map.put(i, "a" + i);
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>//遍历方法1
<span style="white-space:pre">		</span>Set set = map.keySet();
<span style="white-space:pre">		</span>Iterator iterator1 = set.iterator();<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>long startTime1 = Calendar.getInstance().getTimeInMillis(); //开始时间<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>while (iterator1.hasNext()) {
<span style="white-space:pre">			</span>Object key = iterator1.next();
<span style="white-space:pre">			</span>Object value = map.get(key);
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>long endTime1 = Calendar.getInstance().getTimeInMillis();
<span style="white-space:pre">		</span>System.out.println("costTime1 = " + (endTime1 - startTime1)); //结束时间
<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>//遍历方法2
<span style="white-space:pre">		</span>Iterator iterator2 = map.entrySet().iterator();
<span style="white-space:pre">		</span>long startTime2 = Calendar.getInstance().getTimeInMillis(); //开始时间
<span style="white-space:pre">		</span>while (iterator2.hasNext()) {
<span style="white-space:pre">			</span>Map.Entry<Integer, String> entry = (Map.Entry<Integer, String>) iterator2.next();
<span style="white-space:pre">			</span>Object key = entry.getKey();
<span style="white-space:pre">			</span>Object val = entry.getValue();
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>long endTime2 = Calendar.getInstance().getTimeInMillis(); //结束时间
<span style="white-space:pre">		</span>System.out.println("costTime2 = " + (endTime2 - startTime2));
<span style="white-space:pre">	</span>}
}
输出结果:
costTime1 = 145
costTime2 = 78

HashMap的keySet遍历和entrySet遍历时间效率比较,布布扣,bubuko.com

HashMap的keySet遍历和entrySet遍历时间效率比较

标签:java   遍历   keyset   entryset   

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

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