How do I clone a java byte array?

后端 未结 4 634
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-10 10:30

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?

4条回答
  •  离开以前
    2020-12-10 11:32

    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 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.

    Thus:

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

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

    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.

    See also

    • Wikipedia/Object copy
    • Java Nuts and Bolts/Arrays

    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 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.

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

    Related questions

    • Difference between various Array copy methods

提交回复
热议问题