文章

HashMap中的keyset与entryset

在学习集合中HashMap时,老分不清keyset和entryset区别和用法。以下均不指定泛型,默认为Object类型。

看源码--在idea中按住Ctrl

HashMap hashMap = new HashMap();

keyset

public Set<K> keySet() {
    Set<K> ks = keySet;
    if (ks == null) {
        ks = new KeySet();
        keySet = ks;
    }
    return ks;
}
/*
Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

返回值:
a set view of the keys contained in this map
*/

可以看出keyset方法返回的是所有的Key

遍历一下

Set keyset = map.keySet();
//1.增强for
for (Object obj ;keyset){
System.out.println(obj +"==" +map.getkey(obj))
}
//2.迭代器
Iterator iterator = keySet.iterator();
while (iterator.hasNext()) {
    Object next =  iterator.next();
}

entryset

public Set<Map.Entry<K,V>> entrySet() {
    Set<Map.Entry<K,V>> es;
    return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
/*
Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

返回值:
a set view of the mappings contained in this map
*/

调用entrySet方法返回 Set<Map.Entry<K,V>>,Entry是对map中Node结点的引用。

Set entrySet = hashMap.entrySet();
//(1) 增强for
System.out.println("----使用EntrySet 的 for增强(第3种)----");
for (Object obj : entrySet) {
    //将obj 转成 Map.Entry
    Map.Entry m = (Map.Entry) obj;
    //Map.Entry提供getKey与getValue
    System.out.println(m.getKey() + "==" + m.getValue());
}
//(2) 迭代器
System.out.println("----使用EntrySet 的 迭代器(第4种)----");
Iterator iterator = entrySet.iterator();
while (iterator.hasNext()) {
   Object obj =  iterator.next();
   //System.out.println(next.getClass());//HashMap$Node -实现-> Map.Entry (getKey,getValue)
   //向下转型 Map.Entry
   Map.Entry m = (Map.Entry) obj;
   System.out.println(m.getKey() + "==" + m.getValue());
}

通过map中的entrySet方法将K-V封装成Entry,使用增强for循环遍历,需要将接收的entrySet向下转型为Map.Entry(因为Map.entry能够使用get方法获取K-V)

License:  CC BY 4.0