本文实例讲述了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
测试结果:
遍历方式结果分析
由上表可知:
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 条评论) |