Sunday, 12 May 2013

Why Map is not a true Collection?

We saw what are Collections in Java. If you recall the diagram from that post Map does not form a part of Collection though it comes under Collection framework. In more technical terms Map interface does not implement Collection interface. Knowing this the question that naturally comes in mind is why so? Why can't Map be a part of Collection frame work? Let us see the explanation.

Reason for Map interface not extending Collection interface

  • If you look at the respective data structure you can easily guess why Map is not a part of Collection. Each Collection stores a single value where as a Map stores key-value pair. So methods in Collection interface are incompatible for Map interface.For example in Collection we have add(Object o). What would be such implementation in Map. It doesn't make sense to have such a method in Map. Instead we have a put(key,value)  method in Map.
  • Same argument goes for addAll(), remove(), removeAll() methods. So the main reason is the difference in the way data is stored in Map and Collections.
  • Also if you recall Collection interface implemented Iterable interface i.e any interface with .iterator() method should return an iterator which must allow us to iterate over the values stored in the Collection. Now what would such method return for a Map? Key iterator or a Value iterator? This does not make sense either.
There are ways in which we can iterate over keys and values stores in a Map and that is how it is a part of Collection framework.Do not get confuse here. Let me repeat this - Map is a part of Collection framework but it does not implement Collection interface. We will see in next few posts how Map works internally(that's really an interesting topic) and also how we manipulate data in it.

Just to recall the Collection framework refer to the following diagram -

No comments:

Post a comment

t> UA-39527780-1 back to top