CodeGym /Blog Jawa /Acak /Arrays.copyOf() Metode ing Jawa
John Squirrels
tingkat
San Francisco

# Arrays.copyOf() Metode ing Jawa

## Apa metode Arrays.copyOf () ing Jawa?

Java class java.util.Arrays menehi cara disebut Arrays.copyOf () sing ngasilake salinan array liwati minangka parameter kanggo fungsi iki, ngiring dening nemtokake ukuran. Punika header metode kanggo pangerten cepet.
``````
Arrays.copyOf(int[] templateArray, int length);
``````
Elinga yen "dawa" parameter kapindho yaiku ukuran array salinan sing pengin digawe. Dadi ing kene kita bisa duwe 3 kasus.
• Dawane loro template & salinan array padha.
• Dawane larik salinan luwih gedhe tinimbang dawa larik cithakan.
• Dawane array salinan luwih cilik tinimbang dawane array template.
Ayo goleki conto coding kanggo ndeleng kepiye cara ngatasi kabeh telung skenario kasebut ing ndhuwur.

``````
import java.util.Arrays;
public class ArraysCopyOfMethod {
public static void main(String[] args) {

// Initialize your templateArray which you want a copy of
int[] templateArray = new int[] {1, 2, 3, 4, 5, 6};
System.out.println("Template Array: " + Arrays.toString(templateArray));

// Create a "copy" of template array using
// Arrays.copyOf(int[] array, int arrayLength) method

// CASE 1: Sizes of both template & copy arrays are same
int[] copyArray1 = Arrays.copyOf(templateArray, templateArray.length);
System.out.println("Copy Array 1: " + Arrays.toString(copyArray1));

// CASE 2: Size of copy array > Size of template array
// extra space in copy array is filled with zeros
int[] copyArray2 = Arrays.copyOf(templateArray, 10);
System.out.println("Copy Array 2: " + Arrays.toString(copyArray2));

// CASE 3: Size of copy array < Size of template array
// copy array is only filled with only elements in overlapping size
int[] copyArray3 = Arrays.copyOf(templateArray, 3);
System.out.println("Copy Array 3: " + Arrays.toString(copyArray3));
}

}
``````

### Output

Array Cithakan: [1, 2, 3, 4, 5, 6] Array Salin 1: [1, 2, 3, 4, 5, 6] Array Salin 2: [1, 2, 3, 4, 5, 6, 0, 0, 0, 0] Copy Array 3: [1, 2, 3]

## Kesimpulan

Saiki sampeyan kudu duwe pemahaman logis babagan metode Arrays.copyOf () ing Jawa. Nanging, aja ragu-ragu kanggo eksprimen karo macem-macem input kanggo nambah rasa penasaran sampeyan.
Komentar
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION