首页 > 代码库 > HashMap的keySet遍历和entrySet遍历时间效率比较

HashMap的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 = http://www.mamicode.com/map.get(key);>
输出结果:
costTime1 = 145costTime2 = 78