Why does LinkedHashMap class implement Map interface?

This question already has an answer here:

  • Why do many Collection classes in Java extend the abstract class and implement the interface as well? 10 answers

  • You are right: dropping Map<K,V> from linked hash map's declaration would not change anything. Although LinkedHashMap<K,V> would implement Map<K,V> simply because it extends HashMap<K,V> , the fact that linked hash map derives from a regular hash map is an implementation detail, not a hard requirement.

    Implementing the Map<K,V> interface, on the other hand, is a fundamental requirement. This requirement would not disappear if the designers decided to implement LinkedHashMap<K,V> from scratch, or to rely on some other base class, eg a linked list.

    That is why the designers of LinkedHashMap<K,V> mentioned Map<K,V> explicitly: if at some later day a base class would change due to redesign, the interface would stay in place.


    Well, it is probably for the sake of clarity in the documentation, it adds nothing to the code. It might also be because LinkedHashMap extends HashMap is an implementation detail, what is really important to know is that LinkedHashMap is a Map .


    Practically there is no difference. In my opinion, it was always the case in the JDK classes (the same pattern exists for List and its subclasses). The designers probably still haven't removed this redundant implementation so that nothing breaks in case for example someone relies on reflection to get information about the subtypes. For instance imagine you define the following:

    class MyCustomMap<K, V> extends LinkedHashMap<K, V> implements Map<K, V> {
    
    }
    

    Then the below snippet outputs different results with and without the implements :

    Class<?>[] interfaces = MyCustomMap.class.getInterfaces();
    for (int i = 0; i < interfaces.length; i++) {
        System.out.println(interfaces[i]);
    }
    

    Output:

    interface java.util.Map

    Changing the definition to:

    class MyCustomMap<K, V> extends LinkedHashMap<K, V> {
    
    }
    

    then no interface would be printed.

    链接地址: http://www.djcxy.com/p/92198.html

    上一篇: Ruby和Net :: SCP传输(套接字)的性能问题

    下一篇: 为什么LinkedHashMap类实现Map接口?