// more methods to add/remove HashMap elements, etc. }
If I call the getMap() method on an object of this class then do I get a copy of the object's HashMap member variable, or do I get a reference to it ? If I get a reference then any subsequent modifications made to the returned HashMap will effect the state of the MyClass object's internal HashMap member variable, whereas if I get a copy then the original MyClass object's member HashMap is safe. Therefore I assume that the value returned is actually a copy and not a reference, is this correct ?
Thanks in advance...
author and iconoclast
and therefore a reference to the exact same HashMap object is returned. You could, alternatively, write something like
and return a copy instead, if you so chose. But as far as Java goes, what you see is what you get; Java never, ever magically copies an object behind your back.
Now, as far as design issues go: handing out references to a mutable private member is often a Bad Idea. There are a number of alternatives. One is to return a copy, of course. Another is to return a read-only iterator. A third is to write delegating methods like
which basically allow read-only access to the data without exposing the implementation.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Joined: Dec 06, 2001
Marc makes a good point. In Java we ALWAYS manipulate references to objects, not the objects themselves. When you understand this, hopefully it will help you generalize the concept that you've encountered here in order to see how it works in other contexts.