// Map 介面定義
public interface Map {
interface Entry { // 靜態巢狀介面
K getKey();
V getValue();
// ...
}
Set> entrySet();
}
// HashMap 實作 (JDK 8+)
public class HashMap extends AbstractMap implements Map {
// 內部節點類別,實作 Map.Entry
static class Node implements Map.Entry {
final int hash;
final K key;
V value;
Node next;
Node(int hash, K key, V value, Node next) {
this.hash = hash; this.key = key; this.value = value; this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final V setValue(V newValue) {
V old = value;
value = newValue;
return old;
}
// equals/hashCode/toString 省略...
}
// entrySet() 回傳包裝 Set
public Set> entrySet() {
return new EntrySet(); // 內部類別,迭代遍歷 table 中的 Node
}
}
**各 Map 實作類別的內部節點類別** (如 `HashMap.Node`、`TreeMap.Entry`)。`entrySet()` 迭代器遍歷內部表格,將每個節點**作為 `Map.Entry` 型別回傳**,呼叫端多型調用 `getKey()`/`getValue()` 實際執行節點類別的實作。
Map map = new HashMap<>();
map.put("A", 1); map.put("B", 2);
for (Map.Entry entry : map.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
// 實際執行 HashMap.Node.getKey()/getValue()
}