• 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

Why the keySet() method of HashMap returns a Set<K> rather than a HashSet<K>?

 
Rancher
Posts: 129
15
Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why the keySet() method of HashMap returns a Set<K> rather than a HashSet<K>? And why the values() method returns a Collection<V> rather than a more concrete type?
 
Saloon Keeper
Posts: 15524
364
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1) Because map implementations often return internal types. When you modify the set returned from keySet(), how could that set write through to the original map if it was a HashSet?

2) They don't want to force their subclasses to return a specific type.

3) There's no point. HashSet doesn't add any new methods to the Set interface.
 
Saloon Keeper
Posts: 27807
196
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Likes 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Collections are an abstraction. They can be implemented in many different ways to achieve the same primary results. For example, LinkedList, ArrayList and the venerable Vector. Their internals are quite different, but they all implement an ordered collection with support for adding and removing elements.

If you use the abstract interfaces instead of concrete implementations, you leave yourself a lot more flexibility. If I define a variable as being type List rather than as ArrayList and I later discover that a LinkedList offers better performance for the typical workload then i only need to change 1 statement (the constructor) to swap over versus having to change every reference to that object. This is even more critical if I'm trying to implement a library and don't want to artifically constrain what the library user can do.
 
reply
    Bookmark Topic Watch Topic
  • New Topic