Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > Return a constant reference

Reply
Thread Tools

Return a constant reference

 
 
dmly.usa@gmail.com
Guest
Posts: n/a
 
      07-08-2005
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

 
Reply With Quote
 
 
 
 
Tor Iver Wilhelmsen
Guest
Posts: n/a
 
      07-08-2005
http://www.velocityreviews.com/forums/(E-Mail Removed) 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.
 
Reply With Quote
 
 
 
 
Mike Schilling
Guest
Posts: n/a
 
      07-11-2005

<(E-Mail Removed)> wrote in message
news:(E-Mail Removed) 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.


 
Reply With Quote
 
John Currier
Guest
Posts: n/a
 
      07-14-2005
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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
len(var) is [CONSTANT] equal to len(var) == [CONSTANT]? Tor Erik Soenvisen Python 14 11-23-2006 09:57 PM
what value does lack of return or empty "return;" return Greenhorn C Programming 15 03-06-2005 08:19 PM
"Non-constant" constant can't be used as template argument Martin Magnusson C++ 2 10-08-2004 08:41 AM
Understanding How To Use #ifdef Constant #define Constant Sequence In Multible Files Christopher M. Lusardi C++ 1 09-02-2004 07:43 AM
want to return a constant reference to a... Kent C++ 1 11-11-2003 08:57 AM



Advertisments