2

我正在查看 JDK 7 的源代码 - 特别是 WeakHashMap.java,其中广泛使用了它:

Entry<K,V> p = prev;
Entry<K,V> next = p.next;

但接下来不是 Map.Entry 上定义的方法(据我所知?http://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html

对这个方法的调用是从哪里来的?

4

3 回答 3

5

WeakHashMap不是指Map.Entry,而是指它自己的接口内部实现Map.Entry,一个名为 的类Entry。该类有一个名为 的字段next,它可以访问该字段。

于 2013-05-15T17:11:29.697 回答
0

next不是函数。它是被直接访问的类的成员变量。通常你会看到这个(在 OO 代码中)

public class Foo  
{  
    String bar;  

    public String getBar()  
    {   
        return this.bar;
    }  
}  

.next您看到的语法通常被称为直接成员访问,并且通常不受欢迎。

于 2013-05-15T17:12:01.337 回答
0

它是 WeakHashMap 内部的一个内部类,其中包含对 Entry next 的引用:

private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V>{
    V value;
    final int hash;
    Entry<K,V> next;

    Entry(Object key, V value, ReferenceQueue<Object> queue, int hash, Entry<K,V> next) {
    super(key, queue);
    this.value = value;
    this.hash  = hash;
    this.next  = next;

    // omit others...
}

查看第 682 行的源代码:http: //grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/WeakHashMap.java#WeakHashMap.Entry

这与 HashMap 相同。它有类似的内部类:

static class Entry<K, V> implements Map.Entry<K, V>
于 2014-12-03T19:35:06.483 回答