如何克隆java字节数组? [英] How do I clone a java byte array?

查看:172
本文介绍了如何克隆java字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字节数组,我想复制/克隆,以避免调用代码修改我的内部表示。

I have a byte array which i want to copy/clone to avoid calling code from modifying my internal representation.

如何克隆java字节数组?

How do I clone a java byte array?

推荐答案


JLS 6.4 .5数组类型的成员



数组类型的成员全部如下:

JLS 6.4.5 The Members of an Array Type

The members of an array type are all of the following:


  • 公共最终字段长度,其中包含数组的组件数(长度可以是正数或零)。

  • public 方法 clone ,它会覆盖类中同名的方法 Object 并且不会抛出任何已检查的异常。数组类型 T [] 的克隆方法的返回类型是 T []

  • 从类 Object 继承的所有成员; Object 唯一未被继承的方法是 clone 方法。

  • The public final field length, which contains the number of components of the array (length may be positive or zero).
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].
  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

因此:

byte[] original = ...;
byte[] copy = original.clone();

请注意,对于引用类型数组, clone()本质上是 浅层副本

Note that for array of reference types, clone() is essentially a shallow copy.

此外,Java没有多维数组;它有数组数组。因此, byte [] [] 是一个 Object [] ,并且还受浅拷贝的影响

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.

  • Wikipedia/Object copy
  • Java Nuts and Bolts/Arrays
  • 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?

请注意 clone()返回 new 数组对象。如果您只想将值从一个数组复制到现有数组,则可以使用例如 System.arraycopy

Note that clone() returns a new array object. If you simply want to copy the values from one array to an already existing array, you can use e.g. System.arraycopy.

还有 java.util.Arrays.copyOf ,允许您创建不同长度的副本(截断或填充)。

There's also java.util.Arrays.copyOf that allows you to create a copy with a different length (either truncating or padding).

  • Difference between various Array copy methods

这篇关于如何克隆java字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆