-2

In Java, is it possible to initialize several arrays in one line with the same values?

For example, consider this chunk of code

double[][] array1 = {
   { 4, 5, 1, 3},
   { 5, 6, 3, 4},
   {10,-1, 45,3},
   { 1, 3, 2, 4}
};
double[][] array2 = {
   { 4, 5, 1, 3},
   { 5, 6, 3, 4},
   {10,-1, 45,3},
   { 1, 3, 2, 4}
}

As you can see, both arrays are identical, and they got the same initialization. I wonder if I can declare and assign the same values to both in just one instruction.

I tried:

double[][] array1, array2 = {
   { 4, 5, 1, 3},
   { 5, 6, 3, 4},
   {10,-1, 45,3},
   { 1, 3, 2, 4}
};

But in the case above, only array2 is initialized.

EDIT: I am looking for independent initialization. The solutions proposed in the possible duplicates questions do not address what I am looking for:

In the case of "Initializing multiple variables to the same value in Java", the initializations are for Strings, and there, each String has its own initialization (empty string in each case).

In the other possible duplicate "How to deep copy 2 dimensional array (different row sizes)", it involves an iterative solution, which I already knew, but I am not looking for an iterative solution

Community
  • 1
  • 1
Nicolas
  • 1,320
  • 2
  • 16
  • 28
  • 2
    Possible duplicate of [Initializing multiple variables to the same value in Java](http://stackoverflow.com/questions/6202818/initializing-multiple-variables-to-the-same-value-in-java) – bhooks Dec 30 '15 at 21:00
  • 3
    Not if you intend to mutate them separately; there's no simple way to deep copy an array. – Louis Wasserman Dec 30 '15 at 21:03
  • If you're intending on them pointing to the same data, you can do something similar with two lines: `double[][] array1, array2; array1 = array2 = ;` – phflack Dec 30 '15 at 21:06
  • Possible duplicate of [How to deep copy 2 dimensional array (different row sizes)](http://stackoverflow.com/questions/5563157/how-to-deep-copy-2-dimensional-array-different-row-sizes) is done with int[][] but it really doesn't matter. Same thing. – WalterM Dec 30 '15 at 21:10
  • The solution proposed by phflack is not an actual independent initialization. If you do that and then you change one of the arrays, the other gets changed too. I am not looking for that. – Nicolas Dec 30 '15 at 21:50

1 Answers1

0
public static double[][] deepCopy(double[][] array) {
    double[][] d = new double[array.length][];
    for (int i = 0; i < array.length; i++)
        d[i] = Arrays.copyOf(array[i], array[i].length);
    return d;
}
WalterM
  • 2,686
  • 1
  • 19
  • 26