Array copy

In this chapter you will learn:

  1. Copy array
  2. Copy array

Copy array

Java System class has a method we can use to copy array faster.

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.

The arraycopy( ) method can be used to copy quickly an array of any type from one place to another.

public class Main {
  static byte a[] = {65, 66, 67, 68, 69, 70, 71, 72, 73, 74};
  static byte b[] = {77, 77, 77, 77, 77, 77, 77, 77, 77, 77};
//from  j a  v  a2  s  . c om
  public static void main(String args[]) {
    System.out.println("a = " + new String(a));
    System.out.println("b = " + new String(b));
    System.arraycopy(a, 0, b, 0, a.length);
    System.out.println("a = " + new String(a));
    System.out.println("b = " + new String(b));
    System.arraycopy(a, 0, a, 1, a.length - 1);
    System.arraycopy(b, 1, b, 0, b.length - 1);
    System.out.println("a = " + new String(a));
    System.out.println("b = " + new String(b));
  }

}

The output:

Copy array

import java.util.Arrays;
//from j a  va 2  s.c  o m
public class Main
{
    public static void main(String args[])
    {
        int arrayOriginal[] = {42, 55, 21};
        int arrayNew[] = Arrays.copyOf(arrayOriginal, 3);
        printIntArray(arrayNew);
    }

    static void printIntArray(int arrayNew[])
    {
        for (int i : arrayNew)
        {
            System.out.print(i);
            System.out.print(' ');
        }
        System.out.println();
    }
}

Next chapter...

What you will learn in the next chapter:

  1. Compare two arrays
  2. Compare two two-dimensional array
  3. Compare two arrays by reference
Home » Java Tutorial » Array
Java Array
Create an Array
Array Index and length
Multidimensional Arrays
Array examples
Array copy
Array compare
Array Binary search
Array Search
Array sort
Array to List
Convert array to Set
Array fill value
Array to String
Array element reverse
Array element delete
Array shuffle
Array element append
Array min / max value
Sub array search
Get Sub array
Array dimension reflection
Array clone