search
HomeJavajavaTutorialJava understands array copy through underlying source code

This article brings you relevant knowledge about java. It mainly introduces the detailed analysis of understanding array copy through the underlying original code, including loop copying of array, Arrays.copyOf method, Arrays.copyofRange method and so on, let’s take a look at it together, I hope it will be helpful to everyone.

Java understands array copy through underlying source code

Recommended study: "java video tutorial"

Loop to copy the array

Use the loop to copy the array Copying is very simple, just use a loop to assign the elements of the array to be copied to the new array one by one. The specific code implementation is as follows:

public static void main(String[] args) {
        int[] arr = {1,2,3,4,5};
        int[] copy = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            copy[i] = arr[i];
        }
    }

This is the method we generally think of. Here are some more convenient methods provided by JAVA for us.

Arrays.copyOf method

Because I am copying an integer array, I use the Arrays.copyOf method of copying an integer array. Arrays of other types can also be copied, not just integer arrays.

Let’s explain the Arrays.copyOf method by copying an integer array. Let’s first take a look at the underlying original code of the Arrays.copyOf method:

public static int[] copyOf(int[] original, int newLength) {
        int[] copy = new int[newLength];
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }

We can see the Array.copyOf method The return value is an integer array, and the formal parameter has two parameters, one is an integer array, and the other is an integer variable.

The integer array in the formal parameter is the name of the array we want to copy

The integer variable in the formal parameter is the length of the array we want to copy

Because there is a return value, so when we use the Arrays.copyOf method, we need an array to receive the return value. The code is implemented as follows:

public static void main(String[] args) {
        int[] arr = {1,2,3,4,5};
        int[] copy =Arrays.copyOf(arr,arr.length);
    }

Note: The length of the copy can exceed the length of the array to be copied. If it exceeds the length of the array to be copied, the value of the extra element will be 0; for example: I want to copy arr array, but the size of the arr array is 5. If I change arr.length*2 when copying, then the size of the copied array becomes 10, and the value of 6~10 elements is 0. This is also considered expansion. .

Arrays.copyofRange method

If we want to copy part of a partial array, we can use the Arrays.copyRange method. The same as above, we also use copying an integer array to explain. Let’s first take a look at its underlying original code:

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

We can see from the original code of Arrays.copyRange that the return value is an integer array, and The formal parameter is an integer array and two integer variables.

The integer array in the formal parameter is the array name of the array to be copied.

The two integer variables from and to in the formal parameter are the range of the array elements you want to copy. Pay attention to this. The range is [form, to), which is closed on the left and open on the right, excluding the element at the position of to. The code is implemented as follows:

public static void main(String[] args) {
        int[] arr = {1,2,3,4,5};
        int[] copy = Arrays.copyOfRange(arr,1,3);
    }

Note: The array subscript starts from 0, and the elements from 1 to 3 refer to 2, 3, and 4. But the right side is an open interval, so 4 is not included, so copy this The array knowledge copies the two elements 2 and 3.

System.arraycopy method

Then let’s talk about the System.arraycopy method. In fact, careful students have discovered that there is a System.arraycopy method in the original code of the previous two methods. Their bottom layer is also implemented by the System.arraycopy method. Let’s take a look at its underlying original code first

public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

System.arraycopy cannot see the original code implemented. The reason is that native, its underlying layer is C/C to achieve. But the advantage of the native method is that it executes very quickly. The code is implemented as follows:

public static void main(String[] args) {
        int[] arr = {1,2,3,4,5};
        int[] copy = new int[arr.length];
        System.arraycopy(arr,0,copy,0,arr.length);
    }

At this time, the entire array of arr is copied. If you want to make a partial copy, you can complete the partial copy by changing the formal parameters.

clone method

Finally One is the array name.clone method. You only need to understand this method. The code is implemented as follows:

public static void main(String[] args) {
        int[] arr = {1,2,3,4,5};
        int[] copy = arr.clone();
    }

The copy is completed. This method mainly produces a copy of the object, but the address is still different.

Recommended study: "java video tutorial"

The above is the detailed content of Java understands array copy through underlying source code. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:脚本之家. If there is any infringement, please contact admin@php.cn delete
Why is Java a popular choice for developing cross-platform desktop applications?Why is Java a popular choice for developing cross-platform desktop applications?Apr 25, 2025 am 12:23 AM

Javaispopularforcross-platformdesktopapplicationsduetoits"WriteOnce,RunAnywhere"philosophy.1)ItusesbytecodethatrunsonanyJVM-equippedplatform.2)LibrarieslikeSwingandJavaFXhelpcreatenative-lookingUIs.3)Itsextensivestandardlibrarysupportscompr

Discuss situations where writing platform-specific code in Java might be necessary.Discuss situations where writing platform-specific code in Java might be necessary.Apr 25, 2025 am 12:22 AM

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.

What are the future trends in Java development that relate to platform independence?What are the future trends in Java development that relate to platform independence?Apr 25, 2025 am 12:12 AM

Java will further enhance platform independence through cloud-native applications, multi-platform deployment and cross-language interoperability. 1) Cloud native applications will use GraalVM and Quarkus to increase startup speed. 2) Java will be extended to embedded devices, mobile devices and quantum computers. 3) Through GraalVM, Java will seamlessly integrate with languages ​​such as Python and JavaScript to enhance cross-language interoperability.

How does the strong typing of Java contribute to platform independence?How does the strong typing of Java contribute to platform independence?Apr 25, 2025 am 12:11 AM

Java's strong typed system ensures platform independence through type safety, unified type conversion and polymorphism. 1) Type safety performs type checking at compile time to avoid runtime errors; 2) Unified type conversion rules are consistent across all platforms; 3) Polymorphism and interface mechanisms make the code behave consistently on different platforms.

Explain how Java Native Interface (JNI) can compromise platform independence.Explain how Java Native Interface (JNI) can compromise platform independence.Apr 25, 2025 am 12:07 AM

JNI will destroy Java's platform independence. 1) JNI requires local libraries for a specific platform, 2) local code needs to be compiled and linked on the target platform, 3) Different versions of the operating system or JVM may require different local library versions, 4) local code may introduce security vulnerabilities or cause program crashes.

Are there any emerging technologies that threaten or enhance Java's platform independence?Are there any emerging technologies that threaten or enhance Java's platform independence?Apr 24, 2025 am 12:11 AM

Emerging technologies pose both threats and enhancements to Java's platform independence. 1) Cloud computing and containerization technologies such as Docker enhance Java's platform independence, but need to be optimized to adapt to different cloud environments. 2) WebAssembly compiles Java code through GraalVM, extending its platform independence, but it needs to compete with other languages ​​for performance.

What are the different implementations of the JVM, and do they all provide the same level of platform independence?What are the different implementations of the JVM, and do they all provide the same level of platform independence?Apr 24, 2025 am 12:10 AM

Different JVM implementations can provide platform independence, but their performance is slightly different. 1. OracleHotSpot and OpenJDKJVM perform similarly in platform independence, but OpenJDK may require additional configuration. 2. IBMJ9JVM performs optimization on specific operating systems. 3. GraalVM supports multiple languages ​​and requires additional configuration. 4. AzulZingJVM requires specific platform adjustments.

How does platform independence reduce development costs and time?How does platform independence reduce development costs and time?Apr 24, 2025 am 12:08 AM

Platform independence reduces development costs and shortens development time by running the same set of code on multiple operating systems. Specifically, it is manifested as: 1. Reduce development time, only one set of code is required; 2. Reduce maintenance costs and unify the testing process; 3. Quick iteration and team collaboration to simplify the deployment process.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.