keySet()与entrySet()

  1. importjava.util.Calendar;
  2. importjava.util.Date;
  3. importjava.util.HashMap;
  4. importjava.util.Iterator;
  5. importjava.util.Map.Entry;
  6. /**
  7. *测试keySet()与entrySet()的迭代时间
  8. *keySet():迭代后只能通过get()取key
  9. *entrySet():迭代后可以e.getKey(),e.getValue()取key和value。返回的是Entry接口
  10. *最后说明下keySet()的速度比entrySet()慢了很多。看来以后要考虑用entrySet()了
  11. *@authorYL
  12. *@date2009.6.10
  13. */
  14. publicclassHashMapTest
  15. {
  16. publicstaticvoidmain(String[]args)
  17. {
  18. HashMap<String,String>kmap=newHashMap<String,String>();
  19. HashMap<String,String>emap=newHashMap<String,String>();
  20. //装数据
  21. for(inti=0;i<1000;i++)
  22. {
  23. kmap.put(""+i,"YL");
  24. }
  25. for(inti=0;i<1000;i++)
  26. {
  27. emap.put(""+i,"ZT");
  28. }
  29. longstimes=System.currentTimeMillis();
  30. longctimes=Calendar.getInstance().getTimeInMillis();
  31. longdtimes=newDate().getTime();
  32. //初始时间这里我用了三种取值方式最后发现System.currentTimeMillis();是最直接的取值方法
  33. System.out.println(stimes+""+ctimes+""+dtimes);
  34. Iterator<String>ktor=kmap.keySet().iterator();
  35. while(ktor.hasNext())
  36. {
  37. System.out.println(ktor.next());
  38. }
  39. longstimes1=System.currentTimeMillis();
  40. longctimes1=Calendar.getInstance().getTimeInMillis();
  41. longdtimes1=newDate().getTime();
  42. //结束世界并且也是entrySet的开始时间
  43. System.out.println((stimes1-stimes)+""+(ctimes1-ctimes)+""+(dtimes1-dtimes));
  44. System.out.println(stimes1+""+ctimes1+""+dtimes1);
  45. Iterator<Entry<String,String>>itor=emap.entrySet().iterator();
  46. while(itor.hasNext())
  47. {
  48. Entry<String,String>e=itor.next();
  49. //System.out.println(e.getKey());
  50. System.out.println(e.getValue());
  51. }
  52. longstimes2=System.currentTimeMillis();
  53. longctimes2=Calendar.getInstance().getTimeInMillis();
  54. longdtimes2=newDate().getTime();
  55. System.out.println(stimes2+""+ctimes2+""+dtimes2);
  56. System.out.println((stimes2-stimes1)+""+(ctimes2-ctimes1)+""+(dtimes2-dtimes1));
  57. }
  58. }

你可能感兴趣的:(entrySet)