For the copy of the array, at the beginning of the most prone to make a mistake, that is, you think of the application of an array, and then assign the existing array to the new request array name, so it is wrong, so just copy the address of the array in the past, not to copy the elements in the array past, such a copy in the c\c+ The + is called a shallow copy.
The same words don't say much, on the code.
A typical error example (Test2.java):------------------------------------------------------------------------------- Public classtest2{ Public Static voidmain (String [] args) {int[] arr1 = {1,2,3,4,5}; //Note: This is not the copy of the array, but the address copy, that is, arr1 and arr2 point to the same address space int[] arr2 =arr1; arr2[2]=10; for(intnum:arr1) { //the output is: 1 2 4 5System.out.print (num+ "\ T"); } }}-------------------------------------------------------------------------------
Now that you know the cause of the error, you can solve the problem from the root cause, here are two options.
The first scenario:
1 a solution (Test3.java):2 3-------------------------------------------------------------------------------4 //Copying of arrays5 6 Public classtest37 {8 Public Static voidmain (String [] args)9 {Ten int[] A = {1,2,3,4,5}; One A intLen =arr1.length; - int[] arr2 =New int[Len]; - for(inti=0; I<len; i++) the { -Arr2[i] =Arr1[i]; - } - + //the above method is equivalent to the following - //int [] arr2 = (int[]) arr1.clone (); + AARR2[2] = 10; at - for(intnum:arr1) - { - //Printed Results: 1 2 3 4 5 -System.out.print (num+ "\ T"); - } in - System.out.println (); to + for(intnum:arr2) - { the //Printed Result: 1 2 4 5 *System.out.print (num+ "\ T"); $ }Panax Notoginseng } -}
The second option is detailed in the next article.
Copying of arrays (Test2.java, Test3.java)