Hi,
set the methods array parameter as final so that its reference cant
change and
create a copy of the array to work with so that the original values
dont change.
Chris
josh schreef:
> Hi, if I wanted that in a method an argument cannot change its
> reference or cannot
[quoted text clipped - 3 lines]
>
> public static void passMe(int a[])
In Java, it is customary to use the syntax int[] a. int a[] is a C
heritage.
> {
> a[1] *= 10;
>
> // or
> // a = new int[3]; I don't want .....
> }
You are confusing two things: changing the value of what a is
referencing, or changing the reference. Arrays are objects, so you
cannot forbid anyone to change its state (i.e. change its elements).
You can, however, claim that you aren’t going to change the reference,
by doing
public static void passMe(final int[] a)
but the use of this is questionable, since it is still possible to
change the elements of a.
> public static void main(String[] args)
> {
[quoted text clipped - 8 lines]
>
> here in the example x[1] value is changed.....
Then pass a copy of x. If you don’t want others to meddle with your
objects, then don’t pass them to them.
passMe(x.clone())
H.
- --
Hendrik Maryns
http://tcl.sfs.uni-tuebingen.de/~hendrik/
==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html
Oliver Wong - 23 Oct 2006 15:40 GMT
> Then pass a copy of x. If you don't want others to meddle with your
> objects, then don't pass them to them.
>
> passMe(x.clone())
Alternatively, create a new class which wraps around your mutable
object, and only expose read-only methods.
passMe(new ReadOnlyArray(x));
Alternatively, document the method as not modifying its parameter, so
that implementors know not to modify the parameters. This assumes you're not
working with other implementors who might be malicious (i.e. it assumes
you're not writing some sort of security tool)
/**
* Does something. Does NOT modify a.
*/
public void passMe(int[] a) {
}
- Oliver
Robert Klemme - 23 Oct 2006 21:36 GMT
>> Then pass a copy of x. If you don't want others to meddle with your
>> objects, then don't pass them to them.
[quoted text clipped - 3 lines]
> Alternatively, create a new class which wraps around your mutable
> object, and only expose read-only methods.
Actually, he needs not create a new class. This should do the job (from
memory):
Collections.unmodifiableList(Arrays.asList(foo))
Kind regards
robert