Return a constant reference

D

dmly.usa

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
 
M

Mike Schilling

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

John Currier

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
 

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

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top