Java – Reason HashMap does not implement Iterable interface?

collectionsjava

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

Best Answer

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.