7

Javadocs of LinkedHashMap in JDK8:

Invoking the put or get method results in an access to the corresponding entry (assuming it exists after the invocation completes). The putAll method generates one entry access for each mapping in the specified map, in the order that key-value mappings are provided by the specified map's entry set iterator. No other methods generate entry accesses.

Why doesn't new Map methods generate entry accesses on LinkedHashMap? Especially getOrDefault(). Doesn't this violate principle of least astonishment?

@PeterLawrey it is clear from the source code:

getOrDefault is overriden in HashMap:

public V getOrDefault(Object key, V defaultValue) {
     Node<K,V> e;
     return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
}

LinkedHashMap extends HashMap and overrides only get():

public V get(Object key) {
    Node<K,V> e;
    if ((e = getNode(hash(key), key)) == null)
        return null;
    // generating entry access -- comment by me
    if (accessOrder)
        afterNodeAccess(e);
    return e.value;
}

Thus, entry access is not generated by getOrDefault().

leventov
  • 14,760
  • 11
  • 69
  • 98
  • As getOrDefault() must be implemented using get() so it should have the same symantics, have you test that this method doesn't change the access order? – Peter Lawrey Dec 07 '13 at 10:26
  • @PeterLawrey see question edit – leventov Dec 07 '13 at 10:33
  • 2
    It's an interesting question, but I voted to close, since I'm pretty sure answers, unless coming from the writer's of the class, will be opinion based. – Steve P. Dec 07 '13 at 10:43
  • @SteveP. I wrote to core-libs-dev mailing list about a month ago, but my message didn't pass moderation... – leventov Dec 07 '13 at 10:48
  • I suggest sending an email to jdk8-dev@openjdk.java.net – nobeh Dec 07 '13 at 11:15
  • If you feel strongly enough, you may want to consider filing a bug report, but it'll probably be more constructive to ask via jdk8-dev. – Confusion Dec 07 '13 at 12:17
  • @Confusion I've already asked via jdk8-dev. But I suspect nobody moderates these mailing lists – leventov Dec 07 '13 at 12:21
  • 2
    @leventov, the only issue with moderation for many the OpenJDK mailing lists is that posts are restricted to members of the list. So in general, if you want to post a message, you have to join the list first. I don't think anyone decided to drop your message because it was irrelevant or anything. I suspect there's a large moderation queue piling up somewhere because no one is monitoring it. – Stuart Marks Dec 08 '13 at 17:57
  • 1
    A bug report has been filed: https://bugs.openjdk.java.net/browse/JDK-8029795 – aioobe Dec 09 '13 at 11:27

0 Answers0