Java 中复制字节数组的方法

在 Java 编程中,复制字节数组是一个常见的操作,无论是为了数据备份、数据传输还是其他目的,Java 提供了多种方法来复制字节数组,以下是几种常见的方法及其实现。
使用 System.arraycopy 方法
System.arraycopy 是 Java 中用于复制数组的一种方法,它可以直接在底层数组上进行操作,从而提高效率。
代码示例
public class ArrayCopyExample {
public static void main(String[] args) {
byte[] source = {1, 2, 3, 4, 5};
byte[] destination = new byte[source.length];
System.arraycopy(source, 0, destination, 0, source.length);
// 输出复制后的数组
for (byte b : destination) {
System.out.print(b + " ");
}
}
}
使用 Arrays.copyOf 方法
Arrays.copyOf 方法是 Java 5 引入的,它提供了对原始数组的深拷贝,这意味着如果原始数组中有对象引用,新数组中的对象也会是新的实例。

代码示例
import java.util.Arrays;
public class ArrayCopyOfExample {
public static void main(String[] args) {
byte[] source = {1, 2, 3, 4, 5};
byte[] destination = Arrays.copyOf(source, source.length);
// 输出复制后的数组
for (byte b : destination) {
System.out.print(b + " ");
}
}
}
使用 Arrays.copyOfRange 方法
Arrays.copyOfRange 方法用于复制数组的一部分到新的数组中,它允许你指定源数组的起始和结束索引。
代码示例
import java.util.Arrays;
public class ArrayCopyOfRangeExample {
public static void main(String[] args) {
byte[] source = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
byte[] destination = Arrays.copyOfRange(source, 2, 7);
// 输出复制后的数组
for (byte b : destination) {
System.out.print(b + " ");
}
}
}
使用 for 循环手动复制
如果你需要更多的控制,或者想要避免使用库方法,可以使用 for 循环手动复制字节数组。
代码示例
public class ManualArrayCopyExample {
public static void main(String[] args) {
byte[] source = {1, 2, 3, 4, 5};
byte[] destination = new byte[source.length];
for (int i = 0; i < source.length; i++) {
destination[i] = source[i];
}
// 输出复制后的数组
for (byte b : destination) {
System.out.print(b + " ");
}
}
}
在 Java 中复制字节数组有多种方法,包括使用 System.arraycopy、Arrays.copyOf、Arrays.copyOfRange 以及手动使用 for 循环,选择哪种方法取决于具体的需求和性能考虑。System.arraycopy 和 Arrays.copyOf 提供了足够的性能,并且易于使用,是大多数情况下的首选方法。




















