Array copy
In this chapter you will learn:
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:
Home » Java Tutorial » Array