An array of basic functions (copy)

copy

A copy is to replicate inside the array to another array, first initializes two arrays, and placed inside a value, during copying, the length of the array should be considered, to copy only the height of the array is less than or equal copying length of the array, the array can be copied work.

  public class Array03 {
  public static void main(String[] args){
  int[] a=CreateData(10);      //产生10个元素的一维数组
  int[] b=new int[5];      //定义一个新的数组,其空间为5
  Array01Copy(a,b);
    for(int i=0;i<b.length;i++)
     {
           System.out.print(b[i]+"\t");      //开始进行拷贝
     }
   }

  public static void Array01Copy(int[] a,int[] b)     //void 类型不需要写return
{                                               //拷贝函数段
  if(b.length<=a.length)        //  拷贝的条件,即b的长度小于等于a的长度
   {
     for(int i=0;i<b.length;i++)           //进行拷贝
      {
         b[i]=a[i];
      }  
   }

}

  public static int[] CreateData(int n)         //产生一个随机数组
 {
  int[] a=new int[n];
  for(int i=0;i<a.length;i++)
     {
     a[i]=(int)(Math.random()*10);
     }
  return a;
   }

}

The above code is to write to write the copy function to copy the way, while in JAVA language, have their own stock, that is,System.arraycopyuseimport java.util.ArraysHeader file of the call code does not show the above results, and an array of values ​​before and after that we can copy and copy are printed out, after the code optimization.

  import java.util.Arrays;
  public class Array03 { 
  public static void main(String[] args)
 {
  int[] a=CreateData(10);      //产生10个元素的一维数组
  System.out.println("原始数组显示:");
  System.out.println(Array2str(a));
  int[] b=new int[5];
  System.arraycopy(a,0,b,1,2);    //将a数组中的第i个值从第m个数拷贝给b数组第i个值(a,i,b,i,m)
  System.out.println("目标数组显示:");
  System.out.println(Array2str(b));
}
public static String Array2str(int[] a)
{
 String str="";
  for(int i=0;i<a.length;i++)
  {
     str+=a[i]+"\t";
 }
  return str;
 }
ic static int[] CreateData(int n)

 {

  int[] a=new int[n];

  for(int i=0;i<a.length;i++)
  {
     a[i]=(int)(Math.random()*10);
  }
  return a;
 }
}
Published 16 original articles · won praise 11 · views 655

Guess you like

Origin blog.csdn.net/qq_44981039/article/details/102572708