-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

5
  • 2
    Possible duplicate of Initializing multiple variables to the same value in Java Commented Dec 30, 2015 at 21:00
  • 3
    Not if you intend to mutate them separately; there's no simple way to deep copy an array. Commented Dec 30, 2015 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 = <stuff>; Commented Dec 30, 2015 at 21:06
  • Possible duplicate of How to deep copy 2 dimensional array (different row sizes) is done with int[][] but it really doesn't matter. Same thing. Commented Dec 30, 2015 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. Commented Dec 30, 2015 at 21:50

1 Answer 1

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;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.