Map.entry案例详解 Java( 二 )


看到这里的时候大伙儿估计都明白得差不多了为什么HashMap为什么要选择Entry数组来存放key-value对了吧,因为Entry实现的Map.Entry接口里面定义了getKey(),getValue(),setKey(),setValue()等方法相当于一个javaBean,对键值对进行了一个封装便于后面的操作,从这里我们其实也可以联想到不光是HashMap,譬如LinkedHashMap,TreeMap 等继承自map的容器存储key-value对都应该使用的是Entry只不过组织Entry的形式不一样,HashMap用的是数组加链表的形式,LinkedHashMap用的是链表的形式,TreeMap应该使用的二叉树的形式,不信的话上源码
LinkedHashMap:
/*** The head of the doubly linked list.*//定义了链头private transient Entry<K,V> header;
初始化链表的方法:
void init() {header = new Entry<K,V>(-1, null, null, null);header.before = header.after = header;}
TreeMap:
//定义根节点private transient Entry<K,V> root = null;
再看他的put方法,是不是很面熟(二叉排序树的插入操作)
public V put(K key, V value) {Entry<K,V> t = root;if (t == null) {// TBD:// 5045147: (coll) Adding null to an empty TreeSet should// throw NullPointerException//// compare(key, key); // type checkroot = new Entry<K,V>(key, value, null);size = 1;modCount++;return null;}int cmp;Entry<K,V> parent;// split comparator and comparable pathsComparator<? super K> cpr = comparator;if (cpr != null) {do {parent = t;cmp = cpr.compare(key, t.key);if (cmp < 0)t = t.left;else if (cmp > 0)t = t.right;elsereturn t.setValue(value);} while (t != null);}else {if (key == null)throw new NullPointerException();Comparable<? super K> k = (Comparable<? super K>) key;do {parent = t;cmp = k.compareTo(t.key);if (cmp < 0)t = t.left;else if (cmp > 0)t = t.right;elsereturn t.setValue(value);} while (t != null);}Entry<K,V> e = new Entry<K,V>(key, value, parent);if (cmp < 0)parent.left = e;elseparent.right = e;fixAfterInsertion(e);size++;modCount++;return null;}
ok,明白了各种Map的底层存储key-value对的方式后,再来看看如何遍历map吧,这里用HashMap来演示吧
Map提供了一些常用方法,如keySet()、entrySet()等方法,keySet()方法返回值是Map中key值的集合;entrySet()的返回值也是返回一个Set集合,此集合的类型为Map.Entry 。
so,很容易写出如下的遍历代码
1.Map map = new HashMap();Irerator iterator = map.entrySet().iterator();while(iterator.hasNext()) {Map.Entry entry = iterator.next();Object key = entry.getKey();//}2.Map map = new HashMap();SetkeySet= map.keySet();Irerator iterator = keySet.iterator;while(iterator.hasNext()) {Object key = iterator.next();Object value = https://www.yf-zs.com/redian/map.get(key);//}另外,还有一种遍历方法是,单纯的遍历value值,Map有一个values方法,返回的是value的Collection集合 。通过遍历collection也可以遍历value,如[java] view plain copyMap map = new HashMap();Collection c = map.values();Iterator iterator = c.iterator();while(iterator.hasNext()) {Object value = iterator.next();
到此这篇关于Java Map.entry案例详解的文章就介绍到这了,更多相关Java Map.entry内容请搜索趣讯吧以前的文章或继续浏览下面的相关文章希望大家以后多多支持趣讯吧!

推荐阅读