![]() |
Return a constant reference
I know that in C++ you can return a constant reference to an object
like this: int& foo() { int* temp = new int[3]; return const temp&; } so that user can only read the array but not to modify it. Is there anyway we can do the same thing in Java? I have tried "final" for the array but that make the array a constant even for myself. Thanks |
Re: Return a constant reference
dmly.usa@gmail.com writes:
> Is there anyway we can do the same thing in Java? Only by making "read-only" classes: Use private variables and getters, no setters. |
Re: Return a constant reference
<dmly.usa@gmail.com> wrote in message news:1120832861.902058.127340@g49g2000cwa.googlegr oups.com... >I know that in C++ you can return a constant reference to an object > like this: > > int& foo() > { > int* temp = new int[3]; > return const temp&; > } > > so that user can only read the array but not to modify it. > > Is there anyway we can do the same thing in Java? > I have tried "final" for the array but that make the array a constant > even for myself. There is no way to make an array read-only in Java; there are read-only Lists, and you can return one of those instead. Alternatively, especially for a small array, you can make a copy of the array and let the client do as it will with it. |
Re: Return a constant reference
Note that a read-only List just means that the List itself isn't
modifyable...it doesn't stop anyone from modifying the contained objects. Java's lack of something equivalent to const is aggravating. Also note that foo() wasn't declared to return a read-only array ;) John http://schemaspy.sourceforge.net |
| All times are GMT. The time now is 09:47 PM. |
Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.