Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a array into another array that already has data in it?

Tags:

java

arrays

How would I copy an array say

float arraytobecopied[] = {1.20,2.50,3.60};

to another array that has data in it already say

float newarray[] = {5.20,6.30,4.20};

I want to add the the arraytobecopied to the end of the new array and keep the values in the array. also as a side note this would be an on going process adding to the end of the array every time.

Should i just use a for loop? or is there a better way. (Can't use Array) already tried:(

like image 534
Dakota Miller Avatar asked Jun 11 '13 04:06

Dakota Miller


People also ask

How do I copy one array to another in Javascript?

If your arrays are not huge, you can use the push() method of the array to which you want to add values. The push() method can take multiple parameters so you can use the apply() method to pass the array to be pushed as a collection of function parameters. let newArray = []; newArray. push.


2 Answers

This question has been asked here before, You can see this page for the answer. How can I concatenate two arrays in Java?

Use System.arraycopy

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

like image 136
DevZer0 Avatar answered Oct 21 '22 03:10

DevZer0


You can't increase the size of the original array. But you could create a new array, copy both source arrays into it, and assign your reference variable to it.

For example, here's a sketch of a simple implementation. (An alternative is to use System.arraycopy().)

 float[] newerArray = new float[ newarray.length + arraytobecopied.length ];
 for ( int i = 0; i < newarray.length; ++i ) {
     newerArray[i] = newarray[i];
 }
 for ( int i = 0; i < arraytobecopied.length; ++i ) {
     newerArray[ newarray.length + i ] = arraytobecopied[i];
 }
 newarray = newerArray; // Point the reference at the new array

Alternatively, you could use a java.util.ArrayList, which automatically handles growing the internal array. Its toArray() methods make it easy to convert the list to an array when required.

like image 31
Andy Thomas Avatar answered Oct 21 '22 02:10

Andy Thomas