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遍历时间效率比较
原文地址:http://blog.csdn.net/u011402596/article/details/38561493