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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
