Array of java series

I was going to review the annotation as today's push, but it's too late. Let's take a look at the array. The array is used to store a group of data structures with the same type of data and access the elements in the array through subscripts.

Definition of array

There are two main definitions of arrays: one is to specify the size of the array first, and then assign values according to the subscript of the array element; the other is to directly create an array and assign values, as follows:

//1.定义大小为10的数组
int[] arrayA = new int[10];
int arrayB[] = new int[10];
arrayA[0] = 1;
arrayB[1] = 2;
//2.定义数组并赋值
int[] arrayC = {1,2,3,4,5};

Array essence

Array in Java is actually a class, so two array variables can point to the same array. Observe 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 must be 2. In the above code, the value of array arrayd points to arraye. Its essence is that two arrays arrayd and arraye point to the same array space. When the value of an element in arrayd is modified, the value of the corresponding element in the corresponding arraye also changes, as shown in the following figure:

Note: when an array is passed as a method parameter, it is equivalent to passing an array reference. Therefore, the operation on the array in the method will also affect the original array, which is very important.

Copy of array

In order to obtain elements with the same value for each of the two array elements, we can use arraycopy () provided by java to implement it, as follows:

int[] arrayD = {1,1};
int[] arrayF = new int[3];
/复制数组
System.arraycopy(arrayD,0,arrayF,3);
System.out.println(Arrays.toString(arrayF));

Obviously, the values of array arrayf after the execution of the above code are 1, 1 and 1. If the values of array elements in array arrayd are indirectly modified, the values of array arrayf are 2, 1 and 1, which is the result obtained in combination with the context.

By the way, the meanings of arraycopy method parameters are as follows:

/**
 * 复制数组
 * @param src:原数组
 * @param srcPos:原数组开始被复制的位置
 * @param dest:目标数组
 * @param destPos:目标数组开始的位置
 * @param length:目标数组的长度
 */
public static void arraycopy​(Object src,int srcPos,Object dest,int destPos,int length) {
}

There seem to be so many things to pay attention to in the array. Of course, there are other APIs for operating the array. The assignment between arrays affects the value of the original array, which I didn't notice before. I'll write so much today.

You can choose to pay attention to WeChat official account: jzman-blog get the latest updates, and exchange learning together!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>