如何克隆 Java 字节数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3208899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I clone a java byte array?
提问by JavaRocky
I have a byte array which i want to copy/clone to avoid calling code from modifying my internal representation.
我有一个字节数组,我想复制/克隆它以避免调用代码修改我的内部表示。
How do I clone a java byte array?
如何克隆 Java 字节数组?
采纳答案by polygenelubricants
JLS 6.4.5 The Members of an Array Type
The members of an array type are all of the following:
- The
public final field length
, which contains the number of components of the array (length may be positive or zero).- The
public
methodclone
, which overrides the method of the same name in classObject
and throws no checked exceptions. The return type of the clone method of an array typeT[]
isT[]
.- All the members inherited from class
Object
; the only method ofObject
that is not inherited is itsclone
method.
JLS 6.4.5 数组类型的成员
数组类型的成员如下:
- 的
public final field length
,其中包含所述阵列的组件的数量(长度可以是正的或零)。- 该
public
方法clone
,它覆盖类同名的方法Object
,并没有抛出checked异常。数组类型的 clone 方法的返回类型T[]
是T[]
.- 从 class 继承的所有成员
Object
;唯一Object
不被继承的clone
方法是它的方法。
Thus:
因此:
byte[] original = ...;
byte[] copy = original.clone();
Note that for array of reference types, clone()
is essentially a shallow copy.
请注意,对于引用类型的数组,clone()
本质上是浅拷贝。
Also, Java doesn't have multidimensional arrays; it has array of arrays. Thus, a byte[][]
is an Object[]
, and is also subject to shallow copy.
此外,Java 没有多维数组;它有数组数组。因此, abyte[][]
是 an Object[]
,并且也服从浅拷贝。
See also
也可以看看
Related questions
相关问题
- Deep cloning multidimensional arrays in Java… ?
- How to effectively copy an array in java ?
- How to deep copy an irregular 2D array
- How do I do a deep copy of a 2d array in Java?
Other options
其他选项
Note that clone()
returns a newarray object. If you simply want to copy the values from one array to an already existing array, you can use e.g. System.arraycopy
.
请注意,clone()
返回一个新的数组对象。如果您只是想将值从一个数组复制到一个已经存在的数组,您可以使用 eg System.arraycopy
。
There's also java.util.Arrays.copyOf
that allows you to create a copy with a different length (either truncating or padding).
还java.util.Arrays.copyOf
允许您创建具有不同长度(截断或填充)的副本。
Related questions
相关问题
回答by erickson
It's easy, and it's a great idea to do it.
这很容易,而且这样做是个好主意。
byte[] copy = arr.clone();
Note that the return type of the clone()
method of arrays is the type of the array, so no cast is required.
注意clone()
数组的方法的返回类型是数组的类型,所以不需要强制转换。
回答by TofuBeer
System.arraycopy(src, 0, dst, 0, src.length);
System.arraycopy(src, 0, dst, 0, src.length);
回答by Cooper
In order to avoid a possible Null Pointer Exception I use the following syntax:
为了避免可能的空指针异常,我使用以下语法:
byte[] copy = (arr == null) ? null : arr.clone();