Returning array: reference or deep copy?

K

Ken

If a class contains a private array, and a public method of that class
returns that array using a return statement (e.g., return myArray),
will the caller get a deep copy of the array or a reference to the
encapsulated array? If it is the latter, is there a way to return the
array as a constant so that the caller cannot change the values on the
array?

Thanks!

Ken
 
R

Ryan Stewart

Ken said:
If a class contains a private array, and a public method of that class
returns that array using a return statement (e.g., return myArray),
will the caller get a deep copy of the array or a reference to the
encapsulated array? If it is the latter, is there a way to return the
array as a constant so that the caller cannot change the values on the
array?

Thanks!
Always references. If you want a copy (deep or shallow), you have to do it
yourself. And there is no such thing as a constant return.
 
M

Michael Borgwardt

Ryan said:
Always references. If you want a copy (deep or shallow), you have to do it
yourself. And there is no such thing as a constant return.

Not with arrays, anyway. If you use a List, you can do it via
Collections.unmodifiableList().
 
J

John C. Bollinger

Ryan said:
Always references. If you want a copy (deep or shallow), you have to do it
yourself. And there is no such thing as a constant return.

The array classes all expose public clone() methods, however, so if a
shallow copy of the array is sufficient then

return (ElementType[]) myArray.clone();

Makes for a nice, simple, easy to read paradigm. If "ElementType" is a
primitive type then there is no distinction between shallow and deep
copying, and if it is immutable then performing a deep copy would be
wasteful. In some other circumstances a shallow copy is what you would
want anyway (you want the receiver to be able to mutate the returned
array elements with effects visible to the host object).

If you find that you really do want to make a deep copy of the array
then you might want to consider whether your design can be improved; it
is not necessarily so, but I wouldn't be surprised.


John Bollinger
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top