• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Map does not extend Iterable. Why ?

 
Graeme Byers
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does not Map extend Iterable ?
I notice that (old) Hashtable extends Enumeration.
Thank you.

Additional : HashMap.entrySet() allows 'casting' to a Collection and
iterating + printing each element.

[ September 14, 2008: Message edited by: Graeme Byers ]
[ September 14, 2008: Message edited by: Graeme Byers ]
 
Muhammad Saifuddin
Ranch Hand
Posts: 1324
Android Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Map interface does not implement Collection interface, because it does not contain elements but contains entries of keys and their corresponding values.
 
Thomas Thevis
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does not Map extend Iterable ?

Why should it? If you want to iterate the keys, you have the keySet() method. If you want to iterate the values, you can use the values() method. If you want to iterate the key-value-pairs, you have the already mentioned entrySet() method.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34641
363
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Graeme Byers:
I notice that (old) Hashtable extends Enumeration.

What version of Java are you looking at? In Java 6, we have
 
Muhammad Saifuddin
Ranch Hand
Posts: 1324
Android Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
for the entrySet() method, you can prefer JavaDoc.


as it returns a set view of the mappings contained in this map. and Set interface is already extends with collection.
 
Rob Spoor
Sheriff
Pie
Posts: 20545
56
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sun could have made Map extend Iterable, but that would require that Map itself should have an iterator() method. Imagine all the custom Map implementations that would be broken. It's bad enough they did that with the java.sql interfaces.

Besides, you can iterate over the map by using keySet(), entrySet() or values() - that's 8, 10 or 8 extra characters. Is that so much?


I have suggested that Sun implement the enhanced for loop for Maps as well:

or

Sun said that this wouldn't be implemented before Java 7 (which is logical), and by then it can most likely be implemented using closures. Therefore, don't expect to see it at all, so you'll be stuck using Map.Entry:
 
Graeme Byers
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Rob, that's a good reply.
I was just working through the Collection methods and it seemed rather 'missing'.
Graeme.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic