settingsAccountsettings
Menusettings

Q: Copy an array from one to another

+14 votes

Can I copy one array to another in Java (or particular elements of it)? I want to copy particular elements of an integer array to another array without the use of StringBuilder. Is there a method of some class which can do this task? thanks

asked in Java category by user samfred5830
edited by user golearnweb

1 Answer

+2 votes
 
Best answer

You can make use of the System Class and its method: .arraycopy();

Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.

arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

Here's it's use in my code (SEE LINE 21):

package com.tutorials7.java.useful_codes;

public class CopyArray {
    public static void main(String[] args) {
        System.out.println("An array to be copied:");
        int[] arrayForCopy = new int[10];

        for (int i = 0; i < arrayForCopy.length; i++) {
            arrayForCopy[i] = i * 100;
        }

        for (int value : arrayForCopy) {//PRINTING THE ARRAY: arrayForCopy
            System.out.println(value);
        }

        System.out.println();

        System.out.println("Copying the array:");
        int[] copiedArray = new int[5];

        System.arraycopy(arrayForCopy, 5, copiedArray, 0, 5);//USING CLASS System AND IT'S METHOD .arraycopy() FOR COPYING THE INITIAL ARRAY: arrayForCopy TO: copiedArray; FROM 0 TO 5th ELEMENT

        for (int i : copiedArray) {//PRINTING THE ARRAY: copiedArray
            System.out.println(i);
        }
    }
}

The output:

An array to be copied:
0
100
200
300
400
500
600
700
800
900

Copying the array:
500
600
700
800
900

answered by user paulcabalit
selected by user golearnweb
...