Sunday, 22 June 2014

Why Doesn't the Map Interface Extend the Collection Interface in Java?

 The main reason is that Map and Collection represent two different data models.
  • A Collection represents a group of individual elements.

  • A Map represents key-value pairs (mappings).

Because of this fundamental difference, the Map interface does not extend the Collection interface.

Why doesn't Map extend Collection?

1. A Collection stores only elements

A Collection interface (implemented by List, Set, and Queue) stores a group of individual objects.

List<String> names = List.of("John", "David", "Smith");

Here, each item is a single element.

2. A Map stores key-value pairs

A Map stores data in the form of keys and values.

Map<Integer, String> employees = new HashMap<>();

employees.put(101, "John");
employees.put(102, "David");
employees.put(103, "Smith");

Each entry consists of a key and its corresponding value.

3. Duplicate handling is different

Collection

  • List allows duplicate elements.

  • Set does not allow duplicate elements.

Map

  • Keys must be unique.

  • Values can be duplicated.

Map<Integer, String> map = new HashMap<>();

map.put(1, "Java");
map.put(2, "Java");   // Allowed (duplicate value)
map.put(1, "Spring"); // Replaces the previous value for key 1


4. Their operations are completely different

Collection methods work with elements.

add(E e)
remove(Object o)
contains(Object o)

Map methods work with key-value mappings.

put(K key, V value)
get(Object key)
remove(Object key)
containsKey(Object key)
containsValue(Object value)
Because their APIs are fundamentally different, inheritance would not make sense.

5. A Map can expose collections when needed

Although a Map is not a Collection, it provides methods that return collections of its contents.

map.keySet();      // Returns Set<K>
map.values();      // Returns Collection<V>
map.entrySet();    // Returns Set<Map.Entry<K, V>>

Example:

Map<Integer, String> map = new HashMap<>();
map.put(1, "Java");
map.put(2, "Spring");

Set<Integer> keys = map.keySet();
Collection<String> values = map.values();
Set<Map.Entry<Integer, String>> entries = map.entrySet();

Collection vs Map

CollectionMap
Stores individual elementsStores key-value pairs
Represents a group of objectsRepresents mappings between keys and values
Uses methods like add() and remove()Uses methods like put() and get()
Implemented by List, Set, and QueueImplemented by HashMap, TreeMap, LinkedHashMap, etc.
Elements may or may not be unique (depending on implementation)Keys must be unique; values may be duplicated



Related Posts:--
1) How HashMap works internally in Java?
2) Internal Implementation of TreeMap in Java
3) Internal implementation of ArrayList in Java
4) Collection Interview Questions and Answers in Java
5) Internal Implementation of LinkedList in Java
6) Collection Hierarchy in Java

No comments:

Post a Comment