HashMap的遍历
来源:互联网 发布:风险矩阵法的作用 编辑:程序博客网 时间:2024/06/06 17:37
JDK8之前,可以使用keySet或者entrySet来遍历HashMap,JDK8中引入了map.foreach来进行遍历。
原因:keySet其实是遍历了2次,一次是转为Iterator对象,另一次是从hashMap中取出key所对应的value。而entrySet只是遍历了一次就把key和value都放到了entry中,效率更高。如果是JDK8,使用Map.foreach方法。
keySet源码
final class KeyIterator extends HashIterator implements Iterator<K> { public final K next() { return nextNode().key; } }
entrySet源码:
final class EntryIterator extends HashIterator implements Iterator<Map.Entry<K,V>> { public final Map.Entry<K,V> next() { return nextNode(); } }当要得到某个value时,keySet还需要从HashMap中get,entrySet相比keySet少了遍历table的过程,这也是两者性能上的主要差别。
forEach的本质仍是entrySet,源码如下:
default void forEach(BiConsumer<? super K, ? super V> action) { Objects.requireNonNull(action); for (Map.Entry<K, V> entry : entrySet()) { K k; V v; try { k = entry.getKey(); v = entry.getValue(); } catch(IllegalStateException ise) { // this usually means the entry is no longer in the map. throw new ConcurrentModificationException(ise); } action.accept(k, v); } }
阅读全文
0 0
- HashMap对象的遍历
- HashMap 的遍历
- hashmap的遍历
- Java_ABC_10.HashMap的遍历
- HashMap的遍历键值
- HashMap的遍历
- Hashmap的遍历
- HashMap的遍历方法
- HashMap的遍历
- HashMap HashTable 的遍历
- 遍历HashMap的方法
- android的HashMap遍历
- java HashMap的遍历
- 遍历HashMap的方法
- hashMap的遍历
- hashMap的遍历
- hashmap的遍历方法
- 【java】HashMap的遍历
- 分布式开发简介
- Golang 验证 struct 字段的数据格式
- Android获取应用列表
- log4j的分类打印
- 数据结构
- HashMap的遍历
- 【第二届蓝桥杯】中奖计算
- 二进制快速排序
- 选取表单和表单元素
- jQuery相关API及知识点
- 深入理解 Promise 五部曲:4. 扩展问题
- Java 时区问题解析
- 使用JavaBean和JSP制作自动刷新的日历
- Java的Unsafe类及compareAndSwap浅析