Home > Java > javaTutorial > How to implement shallow copy using Java's Arrays.copyOf?

How to implement shallow copy using Java's Arrays.copyOf?

WBOY
Release: 2023-04-24 19:31:06
forward
818 people have browsed it

1. Shallow copy instructions

Copy all the attributes of the member variables in the prototype object that are value types to the cloned object, and also copy the reference addresses of the member variables in the prototype object that are reference types. Copied to the clone object, that is, if a member variable in the prototype object is a reference object, the address of this reference object is shared between the prototype object and the clone object. Simply put, a shallow copy will only copy the prototype object, but not the object it refers to.

2.Arrays.copyOf() copy

creates a new array (that is, allocates a new memory space), and then calls System.arraycopy( ) copies the contents, assigns to the new array, and returns the new array.

3. Example

public static byte[] copyOfRange(byte[] original, int from, int to) {
    int newLength = to - from;
    if (newLength < 0)
        throw new IllegalArgumentException(from + " > " + to);
    byte[] copy = new byte[newLength];
    System.arraycopy(original, from, copy, 0,Math.min(original.length - from, newLength));
    return copy;
}
Copy after login

In fact, it calls System.arraycopy, so it must be a shallow copy.

The above is the detailed content of How to implement shallow copy using Java's Arrays.copyOf?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template