Deep copy:
System.arraycopy (source array name, starting source element index,
Target array name, starting target element index,
Number of elements to be copied);
Operations on the copied array do not affect the source array.
This complete, element-to-elements replication is called deep copy.
1 Public classJAVA1 {2 Public Static voidMain (string[] args) {3 intI,max;4 int[] nums={2,18,1,27,16};5 int[] newnums=New int[nums.length];6System.arraycopy (nums,0,newnums,0, newnums.length);7Newnums[2]=50;8 for(i=0;i<newnums.length;i++)9System.out.println ("newnums[" +i+ "] is" +newnums[i]);Ten System.out.println (); One for(i=0;i<nums.length;i++) ASystem.out.println ("nuns[" +i+ "] is" +nums[i]); - } -}
Shallow copy:
1 Public classshallowcopy{2 Public Static voidMain (string[] args) {3 inti;4 int[] nums={2,18,1,27,16};5 int[] newnums=New int[nums.length];6newnums=nums;7Newnums[2]=50;8 for(i=0;i<newnums.length;i++)9System.out.println ("newnums[" +i+ "] is" +newnums[i]);Ten System.out.println (); One for(i=0;i<nums.length;i++) ASystem.out.println ("nums[" +i+ "] is" +nums[i]); - } -}
Assignment Statement newnums=nums; The task done by this statement is to assign the address stored in the Nums array to the reference variable newnums. There is no storage space allocated using the newnums array, so you do not need to use the new operator, declare the statement int newnums[]; Is enough.
Deep copy and shallow copy