Joona I Palaste wrote:
harry <sp***********@yahoo.co.uk> scribbled the following:
I have 2 multi-dim arrays
double[][] subTotals = null;
String[][] rowTitles = null;
I want to pass them to a function that initialises & populates them like
so -
loadData( rowTitles, subTotals);
this function contains lines like -
subTotals = new double[15][4];
rowTitles = new String[15][9];
They are then populated but when the funtion exits both arrays are back to
null.
I understand (well think I do) the difference between primitive types &
objects as parameters & thought because this would work or at the very least
the rowTitles array would as it's String's
Java parameter passing is pass-by-value. Reassigning the parameters
inside method does not affect their values outside the method. You'll
have to initialise your arrays outside loadData() and only do the
population in loadData().
Actually the references are passed by value, but the object they point
to is still accessible as if if was passed by reference. Therefore,
whilst you can't make the original reference point to a new object, you
can change the contents of the object, that the references point too.
public void testSettingArrays() {
Holder holder = new Holder();
MultiDimensionalArrays arrays = new MultiDimensionalArrays();
arrays .fillArrays(holder);
assertNotNull(holder.strings);
assertNotNull(holder.doubles);
}
public class MultiDimensionalArrays {
public void loadData(String[][] strings, Double[][] doubles) {
//won't work
}
public void loadData(Holder holder) {
holder.strings = new String[10][10];
holder.doubles = new Double[20][20];
}
}
class Holder {
String[][] strings = null;
Double[][] doubles = null;
}