0

I am trying to add a value to the end of an array. I got this to work for arrays that have a fixed length, but now I need to make it work for arrays of any size. I think a simple for loop would do the trick, I just cannot figure out the syntax.

double[] array2 = new double[array.length + 1];
System.arraycopy(array, 0, array2, 0, array.length);
array2[array.length] = val;
array = array2;

return array2;
inda1
  • 63
  • 1
  • 10

3 Answers3

4

You might want to consider using an ArrayList which you can think of as a Dynamic Array. It's size is dynamic and you can keep adding elements without worrying about the size.

By add a value to the end of an array I'm assuming you wish to insert a value. You can do so with an ArrayList like this:

ArrayList<Double>myArrayList = new ArrayList<Double>();
myArrayList.add(3.14);
myArrayList.add(6.24);

If you wish to convert this ArrayList to an Array, you can look here

Community
  • 1
  • 1
gabbar0x
  • 4,046
  • 5
  • 31
  • 51
0

try following

double[] add(double[] array, double val){
    double[] copy = new double[array.length + 1];
    System.arraycopy(array, 0, copy, 0, array.length);
    copy[array.length] = val;
    return copy;
}
Dharmesh Gohil
  • 324
  • 2
  • 6
0

You got two options to do this.

First, as what @bholagabbar said, use ArrayList instead.

Option 2, you can double the array size, copy the old array into the new one (which is similar to what ArrayList does under the hood). BTW, adding one extra space is not a good idea to expand an array. If you got 10 new elements and your array is full, you will need to expand the array 10 times and copy all elements in the array for 10 times. If you double the array's size, most of the time, you only need to expand the array once and copy all elements once.

Yaoquan yu
  • 35
  • 7