【问题标题】:HashMap Entry class's recordAccess() method is empty bodyHashMap Entry 类记录 Access() 方法为空体
【发布时间】:2014-06-23 07:34:11
【问题描述】:

API 有这样的注释..

但是它有什么作用呢?因为它有空体方法。

/**
 * This method is invoked whenever the value in an entry is
 * overwritten by an invocation of put(k,v) for a key k that's already
 * in the HashMap.
 */
void recordAccess(HashMap<K,V> m) {
}

【问题讨论】:

标签: java collections hashmap


【解决方案1】:

它的存在是为了被子类覆盖。访问记录时调用它。 LinkedHashMap 子类重写了这个方法,并使用它将经常访问的记录移动到链表的前面。

【讨论】:

  • 但是为什么 put 方法在 HashMap 中调用它呢?
【解决方案2】:

它在LinkedHashMapHashMap 的子类)使用的Entry 子类中有一个方法体。该方法存在于基类Entry 中,以便能够使用基类HashMap 中的通用代码。但是由于访问记录在不是LinkedHashMaps 的HashMaps 中是无用的,所以该方法没有做任何事情。

【讨论】:

  • 但在这种情况下,该方法是从 HashMap 类的 Entry 对象中调用的……它是空的?
  • HashMap 和 LinkedHashMap 共享一些方法。 LinkedHashMap 需要记录访问,而 HashMap 不需要。所以它们都记录了访问,但是 HashMap 使用了一个 Entry 类,它在记录访问时什么都不做,而 LinkedHashMap 使用一个 Entry 子类,它覆盖了实际记录访问的方法。
  • 就是这样,覆盖是可以的,但是为什么要调用它...如果什么都不做...因为它对 HASHMAP 没有意义那么为什么要从 put 方法调用它
  • 因为LinkedHashMap子类也使用了同样的方法,需要记录访问。
【解决方案3】:

在JDK7中,LinkedHashMap中没有put方法,而是重写了类Entry,也就是说LinkedHashMap中的put元素会调用HashMap的put,但是使用LinkedHashMap的recordAccess

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2015-04-13
    • 1970-01-01
    相关资源
    最近更新 更多