entrySet和keySet之比较

时间:2022-03-18 09:29:45

看到一篇写EntrySet和keySet比较的文章(http://ylsuccess.iteye.com/blog/406068),自己动手做了以下实验。

发现entrySet确实比keySet快,特别是在数据量比较少的时候优势很明显。以后迭代就多用entrySet了。


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

/**
* 测试keySet()与entrySet()的迭代时间
* keySet():迭代后只能通过get()取key
* entrySet():迭代后可以e.getKey(),e.getValue()取key和value。返回的是Entry接口
*
*/
public class HashMapTest
{
public static void main(String[] args)
{
HashMap<String,String> kmap = new HashMap<String,String>();

//装数据
for (int i = 0; i < 10000; i++)
{
kmap.put(""+i, "test");
}


long start1 = System.currentTimeMillis();
long sum1 = 0;

Iterator<String> ktor = kmap.keySet().iterator();
while(ktor.hasNext())
{
System.out.println(kmap.get(ktor.next()));
}
sum1 = (System.currentTimeMillis())-start1;
long start2 = System.currentTimeMillis();
Iterator<Entry<String, String>> itor = kmap.entrySet().iterator();
while(itor.hasNext())
{
Entry<String, String> e = itor.next();
//System.out.println(e.getKey());
System.out.println(e.getValue());
}


System.out.println(sum1+" "+(System.currentTimeMillis()-start2));

}
}