0
votes

We know Map is an Interface which is being implemented by classes HashMap, TreeMap...

Since all these implementing classes have same entry pattern (i.e. key-value pair), why should not we have this Entry pattern within Map Interface itself?

What is the purpose to have this Entry pattern separately as Interface that is nested inside Map Interface?

Thanks in advance.

2
A Map is in a sense a collection of Entry objects. How would you expect it to be an entry? Can you give an example of how Map would be defined as an interface/contract to implement Entry? - ernest_k
They could have done that, but since Entry belongs to Map, i believe they wanted to put it inside the Map interface. - Glains
I agree. As you said, Map is a collection of Entry objects but my questions is why we need to have this entry as separate interface by design, since all the map implementing classes have same pattern of objects as entry. Why don't we have all the methods declared in 'Entry' interface is not declared in 'Map' itself? @ Ernest Kiwele - parthiban
@Anonymous The methods of a single Entry are related to that single entry. The methods of a Map are related to all the entries. Entry has a method getKey(), if it was in Map, which key would it return? - jbx

2 Answers

1
votes

The reason Map.Entry is encapsulated within Map is because it is a very intimate strongly coupled interface that is purposely designed to be used with a Map exclusively. For your intents and purposes you can see it as a pair (key and value) representing one single entry in the Map.

Different Map implementations have different requirements about how to store the entries. A HashMap computes the hash code of the key and stores it in its Node implementation (which extends Map.Entry), while TreeMap's Entry has information like the parent entry, the left and right children and the 'colour' of the node (since it is a red-black tree). Each Map implementation has its own requirements, so the Entry was kept as an interface.

0
votes

The Map interface has one purpose - represent a mapping of keys to values. The Map.Entry interface has a different purpose - represent a single key-value pair.

why should not we have this Entry pattern within Map Interface itself?

If you mean to ask why not declare the methods of the Map.Entry interface directly in the Map interface, that wouldn't make much sense, since a Map contains multiple keys and values, so which key and value would the getKey() and getValue() methods return if they were part of the Map interface?

Besides, the Map.Entry interface is useful when you want to iterate over the entries of a Map. You call the entrySet() method and get a Set<Map.Entry<K,V>>.