Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Objects returned by normal get*() methods: references or copies ?

 
James Adams
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's say I have the following class:

public class MyClass
{
// member variable
private HashMap m_map;

// getter method
public HashMap getMap ()
{
return m_map;
}

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


--James
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You've written the getter as



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.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to be clear, even if we implement the method to return a clone, we're actually returning a reference to the clone we've created. We're not returning the object itself.

For details on references and cloning, see Bruce Eckel's "Passing and Returning Objects" appendix in Thinking in Java...

http://www.faqs.org/docs/think_java/TIJ319.htm
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic