[Java Basics] Copy Array

1. Copy the array

Copy the values ​​in one array to another array

System.arraycopy(src, srcPos, dest, destPos, length)

src: the source array
srcPos: the starting position of the data copied from the source array
dest: the target array
destPos: the starting position of the copy to the target array
length: the length of the copy

 

2. Practice

Topic: First prepare two arrays, their length is a random number between 5-10, and initialize the two arrays with random numbers, and then prepare the third array, the length of the third array is the length of the first two with,

           Use System.arraycopy to merge the first two arrays into the third array.

import java.util.Random;

public class random {

public static void main(String[] args){    
 Random r=new Random();
 int ran1[]=new int[r.nextInt(6)+5];
 int ran2[]=new int[r.nextInt(6)+5];
 
 for(int i=0;i<ran1.length;i++) {
	 ran1[i]=(int)(Math.random()*101);
 }
 
 for(int i=0;i<ran2.length;i++) {
	 ran2[i]=(int)(Math.random()*101);
 }
 
System.out.println("数组ran1的内容为:");
 for(int j=0;j<ran1.length;j++) {
	System.out.print(ran1[j]+"  ");
	}
 System.out.println("");
 System.out.println("数组ran2的内容为:");
 for(int j=0;j<ran2.length;j++) {
	System.out.print(ran2[j]+"  ");
	}
 
 int sum[]=new int[ran1.length+ran2.length];
 System.arraycopy(ran1,0,sum,0,ran1.length);
 System.arraycopy(ran2,0,sum,ran1.length,ran2.length);
 
 System.out.println("");
 System.out.println("数组sum的内容为:");
 for(int n:sum) {
	 System.out.print(n+"  ");
 }
	}
}

Note: Friends who are confused about random number generation can jump to: 3 methods of random number generation

Guess you like

Origin blog.csdn.net/qq_44624536/article/details/113488131