Return a constant reference

Discussion in 'Java' started by dmly.usa@gmail.com, Jul 8, 2005.

  1. Guest

    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
    , Jul 8, 2005
    #1
    1. Advertising

  2. 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.
    Tor Iver Wilhelmsen, Jul 8, 2005
    #2
    1. Advertising

  3. <> wrote in message
    news:...
    >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.
    Mike Schilling, Jul 11, 2005
    #3
  4. John Currier Guest

    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
    John Currier, Jul 14, 2005
    #4
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Kent
    Replies:
    1
    Views:
    325
    Karl Heinz Buchegger
    Nov 11, 2003
  2. Christopher M. Lusardi
    Replies:
    1
    Views:
    4,073
  3. Martin Magnusson
    Replies:
    2
    Views:
    492
    John Harrison
    Oct 8, 2004
  4. Tor Erik Soenvisen
    Replies:
    14
    Views:
    544
    Tim Roberts
    Nov 23, 2006
  5. Replies:
    4
    Views:
    331
    Keith Thompson
    Dec 14, 2006
Loading...

Share This Page