• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Collection hierarchy

 
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Both Set and List are a part of Collection interface.

But Map doesn't extend Collection or in other words Map is not a part of Collection interface.

Could you please tell me why it was designed this way? Is there any significance lies somewhere?
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Collection has a method for adding elements. For Map, the only thing that could be added is instances of Map.Entry. But adding any Map.Entry is dangerous, as it requires extra checks to make sure there is no other Map.Entry with the same key. Also, the implementing class of Map.Entry matters.

So instead of having Map extend Collection, Map provides three views to its data that are collections: keySet() returns a Set view of the keys only, values() returns a Collection view of the values only, and entrySet() returns a Set view of the Map.Entry instances. All three allow for removal of elements, but adding can only be done using Map's own put and putAll methods. Calling add or addAll on one of the views will throw a RuntimeException (UnsupportedOperationException if I recall correctly).
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You could see a Map as a collection of key-value pairs. The designers of the Java collections library could have chosen to implement a Map like that, but they didn't. I know other programming languages in which the Map is indeed a Collection of key-value pairs. So, ultimately there's no logical reason why a Map could not possibly be a Collection, it comes down to a design choice that probably Joshua Bloch made years ago. Rob already explained some of the reasons why it might have been designed like this.
 
This is my favorite tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic