Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Java (http://www.velocityreviews.com/forums/f30-java.html)
-   -   Return a constant reference (http://www.velocityreviews.com/forums/t144720-return-a-constant-reference.html)

dmly.usa@gmail.com 07-08-2005 02:27 PM

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


Tor Iver Wilhelmsen 07-08-2005 03:27 PM

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.

Mike Schilling 07-11-2005 05:58 AM

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.



John Currier 07-14-2005 01:19 AM

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.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57