Arrays Copy
The following example shows how to use Arrays.copyOf API.
It copies the specified array, truncating or padding with default uninitialized value
so the copy has the specified length.
package com.bethecoder.tutorials.utils.arrays;
import java.util.Arrays;
public class ArraysCopy {
public static void main ( String [] args ) {
int [] intArray = { 7 , 8 , 6 } ;
System.out.println ( "Before copy : " + Arrays.toString ( intArray )) ;
//Increase the length of array to 6 and copy the Array
int [] intArray2 = Arrays.copyOf ( intArray, 6 ) ;
intArray2 [ 5 ] = 1729 ;
System.out.println ( "Copied array : " + Arrays.toString ( intArray2 )) ;
System.out.println ( "Original array : " + Arrays.toString ( intArray )) ;
System.out.println () ;
boolean [] boolArray = { true, true, true, true, true, true } ;
System.out.println ( "Before copy : " + Arrays.toString ( boolArray )) ;
//Decrease the length of array by 4 and copy the Array
boolean [] boolArray2 = Arrays.copyOf ( boolArray, 4 ) ;
boolArray2 [ 2 ] = false ;
boolArray2 [ 3 ] = false ;
System.out.println ( "Copied array : " + Arrays.toString ( boolArray2 )) ;
System.out.println ( "Original array : " + Arrays.toString ( boolArray )) ;
}
}
It gives the following output,
Before copy : [7, 8, 6]
Copied array : [7, 8, 6, 0, 0, 1729]
Original array : [7, 8, 6]
Before copy : [true, true, true, true, true, true]
Copied array : [true, true, false, false]
Original array : [true, true, true, true, true, true]