Efficiency comparison of four methods of Java array replication
There are many aspects about the basic knowledge of arrays, such as initialization, reference, traversal, one-dimensional arrays and two-dimensional arrays. Today, let's take a look at array replication.
A multiple-choice question from niuke.com:
Which of the following array copy methods of Java language is the most efficient?
A. The for loop is copied one by one
B.System. arraycopy
C.System. copyof
D. Using clone method
Efficiency: system arraycopy>clone>Arrays. Copyof > for loop
1、System. Usage of arraycopy:
Parameters:
SRC - source array. Srcpos - the starting position in the source array. Dest - destination array. Destpos - the starting position in the target data. Length - number of array elements to copy
Application example:
Operation results:
2. Usage of clone:
java. The clone() method of lang. object class is of protected type and cannot be called directly. You need to perform the following operations on the class to be cloned first:
First, the cloned class implements the clonable interface; Then cover the clone () method in this class and call super. in the clone () method. clone(); So, super Clone () can call Java Clone() method of lang.Object class.
Application example:
3. The difference between copying references and copying objects
Copy reference: refers to copying the address of an object, so the address of the copied object copy is the same as that of the source object. In this way, when a value of the copy is changed, the value of the source object is also changed;
Copy object: copies the entire source object. The address of the object copy is different from that of the source object. When a value of the copy is changed, the value of the source object will not change;
Output results:
It can be seen that the addresses of the copied referenced object and the source object are the same, and the addresses of the copied object and the source object are different
4、Arrays. Usage of copyof:
Arrays. Copyof has ten overloaded methods to copy the specified array and return a copy of the original array. See the JDK API for details
summary
The above is all about the simple code examples and efficiency comparison of the four methods of Java array replication in this paper. I hope it will be helpful for you to understand the relevant contents of array replication.