Joona said:
You'll have to wrap the references up in some object and pass that along
to your method. It's the only way. If you still don't like it, feel free
to write your own language.
Or change class Z so that you can modify a Z instead of creating a new
instance. This is only possible if the code for Z is under your
control, of course.
Java simply does not have pass-by-reference, only pass-by-value. People
can get confused about that when they start passing reference types
around, probably more because of the clash of terminology than for any
other reason. When you pass a reference, you are passing that reference
_by_value_, so the dummy argument in the method (initially) contains a
copy of the value of the reference. Assigning a new value to the dummy
does not affect any other variable that contains the original value.
As I understand it, in fact, C and C++ also have only pass-by-value.
They just have a fairly facile way creating multiple levels of
indirection. If you want to emulate C in this [NOT RECOMMENDED] then
you can do this:
[...]
void fooPasser(Foo foo) {
Foo[] fooPtr = new Foo[] { foo };
passByReference(fooPtr);
// now fooPtr[0] != foo
}
void passByReference(Foo[] fooPtr) {
Foo bar = new Foo();
fooPtr[0] = bar;
}
[...]
The syntax is a bit messier than the C equivalent, but the semantics are
as similar as you can get in this case.
John Bollinger
(e-mail address removed)