Can anybody tell me the reason why HashMap
doesn't implement the Iterable
interface?
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.
Map does not extend Iterable.
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 .
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.
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:
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With