Search code examples
javahashmapjvmhashtablehierarchy

What does each hierarchy in java mean?


Looking at Oracle's documentation there are 3 hierarchies in Java

  1. Class Hierarchy
  2. Interface Hierarchy
  3. Enum Hierarchy

Can someone please explain what does each Hierarchy represent and what is their significance?


A subquestion-

It is documented that

HashMap is the Hash table based implementation of the Map interface

as documented in Oracle website HashTable & HashMap falls under Class Hierarchy and Map falls under Interface Hierarchy, then why isn't HashMap, Hashtable and Map represented under same Hierarchy?


Solution

  • In principle, you could show all Java types in one hierarchy. But interfaces support multiple inheritance, therefore a tree is not sufficient to show the hierarchy. Javadoc solves this by displaying affected entries multiply times if they have multiple unrelated ancestors.

    But separating interfaces and ordinary classes reduces the need for multiple entries dramatically. Now, it is needed for the “Interfaces” section at most. In the case of the java.util package, it’s not needed at all, but it would be needed if we merge the sections, as then, ArrayList and Vector would need to be displayed as subtypes of AbstractList and RandomAccess, fore example.

    They wouldn’t need to be displayed as subtypes of List, however, because their supertype AbstractList is a subtype of List already. Likewise, HashMap does not need to be displayed as subtype of Map, because its supertype AbstractMap does implement Map already. On the other hand, if the type trees were merged, its entry would need to be copied to show up under each, Serializable and Cloneable, which shows how distracting such a humongous type tree would be.

    The enum and annotation types are possibly placed into distinct sections to be consistent with the separation of class and interface, as they are declared with distinct syntax as well, i.e. enum and @interface. Or because they are not really creating a hierarchy like the other types. They always have the same supertype and no subtypes that would appear in the API documentation. On the other hand, you could say the same about record types, but as of JDK 17, they do not appear in a distinct section. But this may be just an oversight as record is a new feature.