What is the method for copying Java struct arrays?
In Java, a struct array can typically be represented using an array of classes. To copy a struct array, you can use the copyOf() method from the Arrays class to make a copy. This method will copy the specified length of array elements into a new array.
Here is an example code demonstrating how to copy a struct array.
import java.util.Arrays;
// 定义一个结构体类
class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
// 创建一个结构体数组
Person[] persons = {new Person("Alice", 25), new Person("Bob", 30), new Person("Charlie", 35)};
// 复制结构体数组
Person[] copiedPersons = Arrays.copyOf(persons, persons.length);
// 遍历原数组
System.out.println("Original array:");
for (Person person : persons) {
System.out.println(person.name + " - " + person.age);
}
// 遍历复制数组
System.out.println("\nCopied array:");
for (Person person : copiedPersons) {
System.out.println(person.name + " - " + person.age);
}
}
}
Running the code above, you will see that the content of the original array and the copied array are the same. This is because the Arrays.copyOf() method copies each element of the original array to a new array, thereby achieving the functionality of copying a struct array.