This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Java in General and the fly likes Collection hierarchy Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Collection hierarchy" Watch "Collection hierarchy" New topic

Collection hierarchy

anish jain
Ranch Hand

Joined: Feb 03, 2010
Posts: 129
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?
Rob Spoor

Joined: Oct 27, 2005
Posts: 20183

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).

How To Ask Questions How To Answer Questions
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15036

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.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: Collection hierarchy
It's not a secret anymore!