Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reason HashMap does not implement Iterable interface? [closed]

Can anybody tell me the reason why HashMap doesn't implement the Iterable interface?

like image 217
Amar Avatar asked Oct 17 '13 09:10

Amar


People also ask

Does Map interface extends Iterable?

Java has Iterable interface which is extended by Collection . The Collection is further extended by List , Queue and Set which has their different-different implementations but the unique thing notice is that the Map interface doesn't extend Collection interface.

Does Map inherit from iterable?

Map does not extend Iterable.

What is the problem with HashMap in Java?

By definition a HashMap in Java stores all keys uniquely. Simply, when we try to put more entries with the same key it will override the previously defined value for that key. Hence, when deleting a key after putting multiple values for that key means the key will no longer exist in the HashMap .

Does Map implement collection interface?

The map interface is present in java. util package represents a mapping between a key and a value. The Map interface is not a subtype of the Collection interface.


2 Answers

To be blunt, Map in general (and HashMap in particular) do not implement Iterator because it is not clear what it should be iterating. There are three choices:

  • Keys
  • Values
  • Entries

None of the three choices above look entirely unreasonable: an argument can be made in favor of each of these approaches. In the end, the library designers decided not to make this choice for you, letting programmers pick what to iterate explicitly.

like image 54
Sergey Kalinichenko Avatar answered Sep 23 '22 20:09

Sergey Kalinichenko


Map doesn't implement it but you can use keySet() or values() or entrySet() and all implement iterator as they are sets. See Map javadoc here

like image 38
Manoj Avatar answered Sep 22 '22 20:09

Manoj