Append a Value to a Fixed Array

时间:2016-04-04 18:43:10

标签: java arrays

I am trying to duplicate an array, but make it one more space longer than the original one. In the new space created, I want to set that to the variable "val". I get an error when I try to compile this code, but I do not understand why. The original array has a guaranteed length of 3.

   double[] array2 = new double[4];

   array2[3] = val;

   return array2[3];

2 个答案:

答案 0 :(得分:1)

I would suggest using the Arrays.copyOf here since that would take care of copying over the elements in the old array.

public static double[] addToEnd(double[] array1, double val) {
    // copy over elements; you don't even need to think 
    // about whether the array has 3 elements or a 100 elements
    int[] array2 = Arrays.copyOf(array1, array1.length + 1);

    // val is copied to the last index
    array2[array2.length - 1] = val;

    return array2;
}

答案 1 :(得分:0)

you could try in such a way

private double method() {
    double[] array2 = new double[4];
    double val = 10.0;
    array2[3] = val;
    return array2[3];
}