• Post Reply Bookmark Topic Watch Topic
  • New Topic

Effective Java - Item 5 : Avoid creating unneccessary objects  RSS feed

 
Patricia Samuel
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Everyone,

While going through the Effective Java book, i came across the following paragraph -
For example, the keySet method of the Map interface returns a Set view of the Map object,
consisting of all the keys in the map. Naively, it would seem that every call to keySet would
have to create a new Set instance, but every call to keySet on a given Map object may return
the same Set instance. Although the returned Set instance is typically mutable, all of the
returned objects are functionally identical: When one returned object changes, so do all the
others because they're all backed by the same Map instance


I am not able to understand the meaning behind this. Would anyone like to explain.

Thanks & Regards,
Patricia.
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you take a look at the source code for java.util.AbstractMap (which ships with the JDK), you'll notice that the keySet() refers to a instance variable called keySet, which is an implementation of java.util.Set. The class java.util.HashMap, which extends java.util.AbstractMap defines an inner class called KeySet, which it uses to initialize the inherited keySet field when the keySet() method is invoked for the first time. This particular Set implementation basically forwards to the Map's instance methods and variables and as such always returns an up-to-date view of the Map's contents, more specifically its keys. For this particular Map implementation that also means that if you remove a key from the Set returned by the keySet() method, it will remove the associated Map.Entry from the Map! Results returned by successive invocations of the keySet() method will reflect these changes, and indeed, so will any previously returned results, because the Set is implemented to directly act on data actually contained by the Map instance.

Note that other implementations of the java.util.Map interface might handle this in a completely different way, for instance by not returning the same Set instance and/or by returning a Set implementation that acts as a read-only view, which won't allow you to structurally modify the backing Map (by removing keys).
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because all Sets returned by keySet() would behave exactly the same, there is only one instance. A short example of how this can be implemented:
If the keySet field is not set it will be created. Then every next call to keySet() will return that very same object.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!