-2

I want to add an array to another array of arrays. Can you help me?

 public static double[][] append(double[][] array, double[] value) {
             double[][] result = Arrays.copyOf(array, array.length + value.length);
             for(int i=0;i<value.length;i++){
             result[result.length - 1][i] = value[i];
             }
             return result;
        }
azurefrog
  • 10,785
  • 7
  • 42
  • 56
Stella
  • 21
  • 4

2 Answers2

0

You only have to add one index to the array, and set its value to value. Currently you are trying to add the double values in an array of arrays of doubles.

public static double[][] append(double[][] array, double[] value) {
    array = Arrays.copyOf(array, array.length + 1);
    array[array.length - 1] = value;
}
Bubletan
  • 3,833
  • 6
  • 25
  • 33
0

You are only adding a single array, so change this:

double[][] result = Arrays.copyOf(array, array.length + value.length);

to this:

double[][] result = Arrays.copyOf(array, array.length + 1);

Every array is an object, even primitive arrays. If you were to add System.out.println(result[0].getClass().getSuperClass()); to your code, it would print class java.lang.Object.

This means every element of 'result' is an object. When you call Arrays.copyOf and request a larger array, all of the extra elements are set to null (as specified in the Arrays.copyOf documentation).

Which means you may not legally access result[result.length - 1][i] until you set result[result.length - 1] to a non-null value. Specifically, you want to set it to a new double array.

In Java, all arrays have a typesafe public clone() method, so you can do away with your for-loop, and simply call:

result[result.length - 1] = value.clone();
VGR
  • 40,506
  • 4
  • 48
  • 63