This series will start with Java arrays, which are data structures used to store a group of data with the same type, and access the elements in the array using indices.
- Array Definition
- Essence of Arrays
- Array Copying
Array Definition#
There are mainly two ways to define an array. One is to specify the size of the array first, and then assign values based on the array element indices. The other is to directly create an array and assign values, as shown below:
//1. Define an array with a size of 10
int[] arrayA = new int[10];
int arrayB[] = new int[10];
arrayA[0] = 1;
arrayB[1] = 2;
//2. Define an array and assign values
int[] arrayC = {1,2,3,4,5};
Essence of Arrays#
In Java, arrays are actually classes, so two array variables can point to the same array. Consider the following code:
int[] arrayD = {1,1,1};
int[] arrayE = arrayD;
arrayD[0] = 2;
System.out.println(arrayE[0]);
Obviously, the result of executing the above code is 2. In the above code, the value of arrayD is assigned to arrayE. The essence is that the two arrays arrayD and arrayE point to the same block of array space. When a value of an element in arrayD is modified, the corresponding value in arrayE is also changed, as shown in the following diagram:
Note: When an array is passed as a parameter to a method, it is equivalent to passing the reference of the array. Therefore, operations on the array in the method will also affect the original array. This point is very important.
Array Copying#
To obtain two arrays with the same values for each element, we can use the arraycopy() method provided by Java, as shown below:
int[] arrayD = {1,1,1};
int[] arrayF = new int[3];
// Copy the array
System.arraycopy(arrayD, 0, arrayF, 0, 3);
System.out.println(Arrays.toString(arrayF));
Obviously, after executing the above code, the values of arrayF are 1, 1, 1. If the values of the array elements in arrayD are indirectly modified, the values of arrayF will be 2, 1, 1. This result is obtained based on the context.
By the way, let's briefly explain the meaning of the parameters of the arraycopy method, as shown below:
/**
* Copy an array
* @param src: The original array
* @param srcPos: The starting position in the original array to be copied
* @param dest: The target array
* @param destPos: The starting position in the target array
* @param length: The length of the target array
*/
public static void arraycopy(Object src,
int srcPos,
Object dest,
int destPos,
int length) {
}
These are the things to pay attention to in arrays. Of course, there are other APIs for manipulating arrays. The assignment between arrays encountered above affects the values of the original array, which I didn't notice before. That's all for today.