Do we need "pass by reference" in Java?
Currently the Java language allows to pass method parameters only by value. This means that if one wants to change a parameter in the method and keep the changed value outside the method there is no direct way to do it. For example if you want to write a method to swap values you cannot do it like that:
public void swap(int a, int b) {
int t = a;
a = b;
b = t;
}
you have to do it like that:
public void swap(int[] a, int[] b) {
int t = a[0];
a[0] = b[0];
b[0] = t;
}
Do you think including pass by reference construct similar to C++ "&", Pascal's "var" or C#'s "ref" is a good idea?
in C++ you can do pointers to pointers to .... :)
But in C/C++ you can pass a pointer to the pointer :)
The interesting thing is that despite the pointer operators in C they desided to add the reference operator in C++ just to make it a little bit more convenient and I think they did right!
In C you can do it like that:
void swap(int * a, int * b) {
int t = *a;
*a = *b;
*b = t;
}
then you call:
int a = 2;
int b = 3;
swap(&a, &b);
But in order to save you the constant referencing/dereferencing in C++ they added the & operator, and it looks like that:
void swap(int & a, int & b) {
int t = a;
a = b;
b = t;
}
and you call it like that:
int a = 2;
int b = 3;
swap(a, b);
Cleaner, heh :?)
returning multiple values?
If you want to return multiple values you have no way but to use a wrapper object.
How are you going to do that now:
(1)
public void createMultiple(Object a, Object b) {
a = new Object();
b = new Object();
}
Object a = null;
Object b = null;
createMultiple(a, b);
// a and b are still null after the method call
In order for this to work you have to create a wrapper
(2)
public class Wrapper {
public Object a;
public Object b;
}
public void createMultiple(Wrapper w) {
w.a = new Object();
w.b = new Object();
}
then this will work:
Wrapper w = new Wrapper();
createMultiple(w);
Object a = w.a;
Object b = w.b;
If we have references we do just that
public void createMultiple(Object & a, Object & b) {
a = new Object();
b = new Object();
}
this way the first snippet (1) will work.