Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - paste a given little array into another bigger array at a specified position (or interval)

I would like to paste a given little array into another bigger array at a specified position (or interval) in Java:

int[] bigger_array = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int[] smaller_array = { 1, 2, 3 };

Does exist a simple Java method (with matlab it's simple) that helps me pasting "smaller_array" for example at position 2 (of the bigger) so that "bigger_array" variable becomes:

{ 0, 0, 1, 2, 3, 0, 0, 0, 0 };

Please don't paste methods with a simple "for". I want to know if an optimized method exists.

like image 856
madx Avatar asked Apr 30 '26 21:04

madx


1 Answers

You can use System.arraycopy:

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

Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dest. The number of components copied is equal to the length argument. The components at positions srcPos through srcPos+length-1 in the source array are copied into positions destPos through destPos+length-1, respectively, of the destination array.

Note that the documentation on the System class says (emphasis added):

Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.

Here's an exaple and its output:

import java.util.Arrays;

public class ArrayCopyDemo {
    public static void main(String[] args) {
        int[] bigger_array = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        int[] smaller_array = { 1, 2, 3 };
        // start copying from position 1 in source, and into 
        // position 3 of the destination, and copy 2 elements.
        int srcPos = 1, destPos = 3, length = 2;
        System.arraycopy(smaller_array, srcPos, bigger_array, destPos, length );
        System.out.println( Arrays.toString( bigger_array ));
    }
}
[0, 0, 0, 2, 3, 0, 0, 0, 0]

To copy the entire array, just use 0 as srcPos, and src.length as length (where src is the source array; in this case, you'd use smaller_array.length).

like image 199
Joshua Taylor Avatar answered May 02 '26 10:05

Joshua Taylor