package map_;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@SuppressWarnings({"all"})
public class map3 {
public static void main(String[] args) {
Map maP = new HashMap();
System.out.println(maP.getClass()); //class java.util.HashMap
maP.put("no1","hsp");
maP.put("no2","hsp");
Set set = maP.entrySet();
System.out.println(set.getClass()); // class java.util.HashMap$EntrySet
for (Object o /**o是HashMap$Node*/: set) {
//为了从HashMap$Node取出K-V
//1、先做一个向下转型
Map.Entry entry = (Map.Entry) o;
System.out.println(entry.getClass());
System.out.println(entry.getKey() + "--" + entry.getValue());
}
}
}
一、entrySet为啥类型可以是Set:
1、这里我们可以看entrySet的底层代码:这样entrySet就可以用Set里面定义的方法。
/**
* Holds cached entrySet(). Note that AbstractMap fields are used
* for keySet() and values().
*/
transient Set<Map.Entry<K,V>> entrySet;
二:HashMap里面的static class Node<K,V> implements Map.Entry<K,V>静态内部类实现了Map.Entry<K,V>但是还是不能用getKey和getValue:
在 HashMap 中,Node<K,V> 类是一个静态内部类,但是Node静态内部类的限定符是默认,而不能是public(因为内部类都不可以是public)而May.Entry<K,V>是public类型。
源码:
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
//都不允许被继承重写,实现了接口Map.Entry<K,V>的方法。
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}