Do U Wanna Copy An Array ?

Hi Friends,

To copy an array in JAVA we have 3 options…

1. Manually iterating elements of the source array and placing each one into the destination array using loop.

2. arraycopy() Method of java.lang.System class


Method syntax :-

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

Demo Program

class ArrayCopyDemo {
    public static void main(String[] args) {
        char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
			    'i', 'n', 'a', 't', 'e', 'd' };
        char[] copyTo = new char[7];

        System.arraycopy(copyFrom, 2, copyTo, 0, 7);
        System.out.println(new String(copyTo));
    }
}

The output from this program is:

caffein

3. copyOfRange() Method of java.util.Arrays class

Demo Program

class ArrayCopyOfDemo {
    public static void main(String[] args) {
        
        char[] copyFrom = {'d', 'e', 'c', 'a', 'f', 'f', 'e',
            'i', 'n', 'a', 't', 'e', 'd'};
            
        char[] copyTo = java.util.Arrays.copyOfRange(copyFrom, 2, 9);
        
        System.out.println(new String(copyTo));
    }
}

The output from this program is:

caffein

The difference between 2nd and 3rd is that using the copyOfRange method does not require you to create the destination array before calling the method, because the destination array is returned by the method. Although it requires fewer lines of code.

Refer java docs by Oracle
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

Advertisements

3 thoughts on “Do U Wanna Copy An Array ?

  1. java.lang.System.arraycopy() is different from cloning; during cloning we create a duplicate copy of an array whereas in copying we copy individual elements from one array to another. Java’s static method java.lang.System.arraycopy() is used to copy complete array to another and also for copying selected elements.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s