Map interface doesn’t extend Collection
The Map interface in Java does not extend the Collection interface for several reasons:
1. Conceptual Differences
- Map represents a collection of key-value pairs, where each key maps to exactly one value.
- A Collection represents a group of individual elements.
- The operations and properties of a Map (like put, get, keySet, etc.) are fundamentally different from those of a Collection (like add, remove, iterator, etc.).
2. Method Differences:
- The methods defined in the Collection interface (e.g., add, remove, contains) do not align with the methods needed for a Map.
- A Map requires methods to handle mappings (put, get, remove by key) which are not meaningful for a Collection.
3. Design Considerations
- Extending Collection would impose methods on Map that do not make sense for key-value pairs.
- It would violate the design principle of keeping interfaces cohesive by grouping related methods together.
Table of Contents
Example
To illustrate the conceptual and operational differences between Map and Collection, let’s look at an example:
java
import java.util.*;
public class MapVsCollection {
public static void main(String[] args) {
// Example of a Collection (ArrayList)
Collection<String> collection = new ArrayList<>();
collection.add("Apple");
collection.add("Banana");
collection.add("Cherry");
System.out.println("Collection elements:");
for (String element : collection) {
System.out.println(element);
}
// Example of a Map (HashMap)
Map<String, String> map = new HashMap<>();
map.put("A", "Apple");
map.put("B", "Banana");
map.put("C", "Cherry");
System.out.println("\nMap elements:");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
}
}
Explanation
- Collection Example:
- We use an ArrayList, which is a type of Collection.
- We add elements using the add method and iterate over them using a for-each loop.
- Output: Collection elements:
Apple
Banana
Cherry
Map Example
- We use a HashMap, which is a type of Map.
- We add key-value pairs using the put method and iterate over the entries using a for-each loop.
- Output: Map elements:
A -> Apple
B -> Banana
C -> Cherry
Summary
The Map interface does not extend the Collection interface due to fundamental differences in their conceptual models, methods, and design considerations. The provided Java example illustrates these differences effectively.