4

I am going through how java classes and interfaces designed , just saw the java/util/Map.java and i got below doubt ? please help me by answering.

what is the reason behind the interface Map have inner interface Entry?
Please see the source code of the java/util/Map.java and answer.

1 Answers1

2

Map<K,V> can be viewed as an associative storage (i.e. a container that connects keys to their values). It can also be viewed as a collection of pairs, where the first element is the key, and the second element is its corresponding value.

The majority of methods in Map<K,V> supports the associative container view of the map. Map.Entry<K,V> interface is there to support the other view of the map - i.e. as a collection of key-value pairs.

Each map provides access to so called entry set, which is a set of pairs from the map. Each pair is represented by an instance of Map.Entry<K,V>.

Map<Integer,String> myMap = ...
for (Map.Entry<Integer,String> e : myMap.entrySet()) {
    System.out.println(e.getKey()+" ---> "+e.getValue());
}

One could have defined MapEntry<K,V> interface outside Map<K,V>. However, since the interface is very closely related to the map, a decision to nest the interface inside the map makes perfect sense.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • As per my understanding based on your explanation , since it is very closely related to the map so defined inside the interface. am i right ?thank you for answering. – Narayana Sai May 08 '15 at 04:04
  • Upvote for recognizing what was done well in original JDK. I shall not speak of the abominations. – David J. Liszewski May 08 '15 at 04:17
  • @NarayanaSai Yes, that's right. There is no exact measure for how closely should be that "closely related" thing, but a rule of thumb is that if a class or interface makes sense only in the context of another class or interface (e.g. map entries require a map of which they are entries) then it should probably be a nested class or interface. – Sergey Kalinichenko May 08 '15 at 09:44