首先是一个 关于遍历的小例子:
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String, String> maps = new HashMap<String, String>();
maps.put("111", "111a");
maps.put("222", "222b");
maps.put("333", "333c");
maps.put("444", "444d");
maps.put("555", "555e");
maps.put("666", "666f");
for(String str : maps.keySet()){
System.out.println(str + ":" + maps.get(str));
}
System.out.println("--------------");
for(Entry<String, String> str : maps.entrySet()){
System.out.println(str + " " + str.getKey() + ":" + str.getValue());
}
}
至于这两者的性能:
通过测试发现,第二种方式的性能通常要比第一种方式高一倍。
例子如下:
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接口
* 最后说明下keySet()的速度比entrySet()慢了很多。看来以后要考虑用entrySet()了
* @author YL
* @date 2009.6.10
*/
public class HashMapTest
{
public static void main(String[] args)
{
HashMap<String,String> kmap = new HashMap<String,String>();
HashMap<String, String> emap = new HashMap<String, String>();
//装数据
for (int i = 0; i < 1000; i++)
{
kmap.put(""+i, "YL");
}
for (int i = 0; i < 1000; i++)
{
emap.put(""+i, "ZT");
}
long stimes = System.currentTimeMillis();
long ctimes = Calendar.getInstance().getTimeInMillis();
long dtimes = new Date().getTime();
//初始时间 这里我用了三种取值方式 最后发现System.currentTimeMillis();是最直接的取值方法
System.out.println(stimes+""+ctimes+""+dtimes);
Iterator<String> ktor = kmap.keySet().iterator();
while(ktor.hasNext())
{
System.out.println(ktor.next());
}
long stimes1 = System.currentTimeMillis();
long ctimes1 = Calendar.getInstance().getTimeInMillis();
long dtimes1 = new Date().getTime();
//结束世界并且也是entrySet的开始时间
System.out.println((stimes1-stimes)+""+(ctimes1-ctimes)+""+(dtimes1-dtimes));
System.out.println(stimes1+""+ctimes1+""+dtimes1);
Iterator<Entry<String, String>> itor = emap.entrySet().iterator();
while(itor.hasNext())
{
Entry<String, String> e = itor.next();
//System.out.println(e.getKey());
System.out.println(e.getValue());
}
long stimes2 = System.currentTimeMillis();
long ctimes2 = Calendar.getInstance().getTimeInMillis();
long dtimes2 = new Date().getTime();
System.out.println(stimes2+""+ctimes2+""+dtimes2);
System.out.println((stimes2-stimes1)+""+(ctimes2-ctimes1)+""+(dtimes2-dtimes1));
}
}