SoFunction
Updated on 2025-03-08

Detailed explanation of array copy (clone and arraycopy) code in Java

Copying of JAVA arrays is a reference pass, not a value pass from other languages.

1、clone

protectedObjectclone()

throwsCloneNotSupportedExceptionCreates and returns a copy of this object. The exact meaning of "copy" may depend on the object's class. The purpose of this is that for any object x, the expression:

()!=x is true, expression:

().getClass()==() is also true, but these are not required to meet the requirements. In general:

().equals(x) is true, but this is not a requirement that must be met.

By convention, the returned object should be obtained by calling. If a class and all its superclasses (except Object) comply with this convention,().getClass()==()。

By convention, the object returned by this method should be independent of that object (the object being copied). To obtain this independence, it is necessary to modify one or more fields of the object before returning it. This usually means copying all mutable objects that contain the internal "deep structure" of the objects being copied, and replacing references to those objects with a reference to the copy. If a class contains only basic fields or references to invariant objects, it is usually not necessary to modify the fields in the returned object.

The clone method of the Object class performs a specific copy operation. First, if the class of this object cannot implement the interface Cloneable, a CloneNotSupportedException will be thrown. Note that all arrays are considered to implement interface Cloneable. Otherwise, this method creates a new instance of the class of this object and, like by allocation, strictly initializes all fields of the object with the contents of the corresponding fields of this object; the contents of these fields are not copied by themselves. Therefore, this method performs a "shallow copy" of the object, not a "deep copy" operation.

The Object class itself does not implement the interface Cloneable, so calling the clone method on an object whose class is Object will cause an exception to be thrown at runtime.

return:

A copy of this instance.

Throw:

CloneNotSupportedException - If the object's class does not support the Cloneable interface, a subclass of overriding the clone method will also throw this exception to indicate that an instance cannot be copied.

1. The cloning method is used to create a copy of the object. In order to use the clone method, the class must implement the interface to override the protected method clone.

If the Clonebale interface is not implemented, a CloneNotSupportedException will be thrown.

2. The constructor will not be called when cloning a java object.

3. Java provides a default method called shallowcopy to implement clone. After creating a copy of the object, then copy the content by assigning the value.

It means that if your class contains reference types, then both the original object and the clone will point to the same reference content, which is very dangerous.

Because any changes occurring on a variable field will be reflected on the common content they are citing. To avoid this, deep cloning of the referenced content is required.

2、arraycopy

publicstaticvoidarraycopy(Objectsrc,

intsrcPos,

Objectdest,

intdestPos,

intlength)Copy an array from the specified source array, and copy starts from the specified location and ends at the specified location of the destination array.

From the source array referenced by src to the target array referenced by dest, a subsequence of the array component is copied. The number of the copied component is equal to

length parameter. Components in the source array with positions between srcPos and srcPos+length-1 are copied to the destPos in the target array respectively.

Go to the destPos+length-1 position.

If the parameters src and dest refer to the same array object, the copying process is as if first copying the component from srcPos to srcPos+length-1 to a temporary array with a length component, and then copying the contents of this temporary array to the destPos to destPos+length-1 of the target array.

If if dest is null, a NullPointerException exception is thrown.

If src is null, a NullPointerException exception is thrown and the target array is not modified.

Otherwise, an ArrayStoreException exception is thrown and the target array is not modified as long as any of the following cases are true:

The src parameter refers to a non-array object.

The dest parameter refers to a non-array object.

The src parameter and the dest parameter refer to those arrays whose component types are of different basic types.

The src parameter refers to an array with a base component type and the dest parameter refers to an array with a reference component type.

The src parameter refers to an array with reference component type and the dest parameter refers to an array with basic component type.

Otherwise, if any of the following cases are true, an IndexOutOfBoundsException is thrown and the target array is not modified:

The srcPos parameter is negative.

The destPos parameter is negative.

The length parameter is negative.

srcPos+length is greater than, that is, the length of the source array.

destPos+length is greater than, that is, the length of the target array.

Otherwise, if the actual components in the source array from srcPos to srcPos+length-1 are converted by allocation and cannot be converted into components of the target array

Type, an ArrayStoreException exception is thrown. In this case, set k to the smallest non-negative integer smaller than the length, so that it is impossible

Convert src[srcPos+k] to the component type of the target array; when an exception is thrown, the source array component from srcPos to srcPos+k-1 position

DestPos to destPos+k-1 positions that have been copied to the target array, while other positions in the target array will not be modified.

(Because of those limitations that have been specified in detail, this paragraph can only be effectively applied to

Both arrays have component types with reference types. )

parameter:

src-source array.

srcPos - Start position in the source array.

dest-Array of Targets.

destPos - The starting position in the target data.

length - The number of array elements to be copied.

Throw:

IndexOutOfBoundsException - If copied, it will cause access to data outside the range of the array.

ArrayStoreException - If the elements in the src array cannot be stored in the dest array due to type mismatch.

NullPointerException - If src or dest is null.

3. Test code

import ;
public class TestCloneCopy 
{
	public static void outputArrays(int[] a) 
	  {
		for ( int i = 0; i < ; ++i ) 
		    {
			(a[i] + "\t");
		}
		();
	}
	public static void main(String[] args) 
	  {
		int[] ia = new int[10];
		(ia,20);
		////////////////////////////////////////////////////////////////////clone//////////////////////////////////////////////////////////////// 
		//Clone an array ia		int[] ib = ();
		ib[5] = 11;
		(ib);
		(ia);
		///////////////////////////////////////////////////////////////arraycopy///////////////////////////////////////////////////// 
		int[] ic = new int[20];
		(ib,0,ic,5,10);
		(ic);
	}
}

Test results:

F:\code\Java\Course\017_ArrayCloneCopy>java TestCloneCopy 
20   20   20   20   20   11   20   20   20   20 
 
20   20   20   20   20   20   20   20   20   20 
 
0    0    0    0    0    20   20   20   20   20 
11   20   20   20   20   0    0    0    0    0 

Summarize

The above is all the detailed explanation of the code of array copy (clone and arraycopy) in Java. I hope it will be of some help to everyone in learning Java array copying.