Hvad er Arrays.copyOf()-metoden i Java?
Java-klassen java.util.Arrays giver en metode kaldet Arrays.copyOf() , der returnerer en kopi af et array, der sendes som en parameter til denne funktion, efterfulgt af at angive dens størrelse. Her er metodeoverskriften for hurtig forståelse.
Arrays.copyOf(int[] templateArray, int length);
Bemærk, at den anden parameter "længde" er størrelsen på det kopiarray, du vil oprette. Så her kan vi have 3 sager.
- Længderne af både skabelon- og kopiarrays er de samme.
- Længden af kopiarrayet er større end længden af skabelonarrayet.
- Længden af kopiarrayet er mindre end længden af skabelonarrayet.

Kodningseksempel
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));
}
}
Produktion
Template Array: [1, 2, 3, 4, 5, 6] Kopier Array 1: [1, 2, 3, 4, 5, 6] Kopier Array 2: [1, 2, 3, 4, 5, 6, 0, 0, 0, 0] Kopier Array 3: [1, 2, 3]
GO TO FULL VERSION