首页 > 作文

对象循环遍历(排列组合跟循环的区别)

更新时间:2023-04-05 11:25:09 阅读: 评论:0

本文实例讲述了java hashmap三种循环遍历方式及其性能对比。分享给大家供大家参考,具体如下:

hashmap的三种遍历方式

(1)for each map.entryt()

map<string, string> ma天安门p = new hashmap<string, string>();for (entry秋季钓鱼技巧<string, string> entry : map.entryt()) {  entry.getkey();  e食堂配菜ntry.getvalue();}

(2)显示调用map.entryt()的集合迭代器

iterator<map.entry<string, string>> iterator = map.entryt().iterator();while (iterator.hasnext()) {  entry.getkey();  entry.getvalue();}

(3)for each map.keyt(),再调用get获取

map<string, string> map = new hashmap<string, string>();for (string key : map.keyt()) {  map.get(key);}

三种遍历方式的性能测试及对比

测试环境:windows7 32位系统 3.2g双核cpu 4g内存,java 7,eclip -xms512m -xmx512m

测试结果:

遍历方式结果分析
由上表可知:

for each entryt与for iterator entryt性能等价for each keyt由于要再调用get(key)获取值,比较水上清真寺耗时(若hash散列算法较差,会更加耗时)在循环过程中若要对m意大利的城市ap进行删除操作,只能用for iterator entryt(在hahsmap非线程安全里介绍)。

hashmap entryt源码

public v get(object key) {  if (key == null)    return getfornullkey();  entry<k,v> entry = getentry(key);  return null == entry ? null : entry.getvalue();}/** 1. returns the entry associated with the specified key in the 2. hashmap. returns null if the hashmap contains no mapping 3. for the key. */final entry<k,v> getentry(object key) {  int hash = (key == null) ? 0 : hash(key);  for (entry<k,v> e = table[indexfor(hash, table.length)];     e != null;     e = e.next) {    object k;    if (e.hash == hash &&      ((k = e.key) == key || (key != null && key.equals(k))))      return e;  }  return null;}

结论

循环中需要key、value,但不对map进行删除操作,使用for each entryt循环中需要key、value,且要对map进行删除操作,使用for iterator entryt循环中只需要key,使用for each keyt

本文发布于:2023-04-05 11:25:07,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/beb282fd3b8936821f25bbc640e3bbc3.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:对象循环遍历(排列组合跟循环的区别).doc

本文 PDF 下载地址:对象循环遍历(排列组合跟循环的区别).pdf

下一篇:返回列表
标签:遍历   三种   方式   操作
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图