Why does the LinkedHashMap class implement the Map interface?

The HashMap class implements the map interface:

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable 

The LinkedHashMap class extends HashMap, which means that it must implement the default Map interface. Why does it explicitly implement the Map interface?

 public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> 
+6
source share
4 answers

You are right: dropping Map<K,V> from the associated hash map declaration will not change anything. Although LinkedHashMap<K,V> will implement Map<K,V> simply because it extends HashMap<K,V> , the fact that the associated hash mapping comes from a regular hash map is an implementation detail, not a hard one requirement.

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

This is why LinkedHashMap<K,V> designers explicitly indicated Map<K,V> : if at some later day the base class changes due to the redesign, the interface will remain in place.

+5
source

Well, this is probably for clarity in the documentation, doesn't add anything to the code. It could also be due to the fact that LinkedHashMap extends HashMap is an implementation detail, what is really important to know is that LinkedHashMap is a Map .

+4
source

There is practically no difference. In my opinion, this has always been in JDK classes (the same model exists for List and its subclasses). Designers have probably not yet removed this redundant implementation, so nothing will break if, for example, someone relies on reflection to get information about subtypes. For example, imagine that 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 implements :

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

Output:

java.util.Map interface

Change of definition:

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

then no interface will be printed.

+3
source

Dichi has this right, for the most part.

For a long time, some of the lesser Java compilers might get a little confused, and sometimes I added (to my code) the interfaces that were supposed to be derived from the parent hierarchy. Perhaps this was due to putting the interface in several places (for Java libraries), but this is pure speculation.

+1
source

Source: https://habr.com/ru/post/986362/


All Articles