System.arraycopy实现数组之间的复制以及Arrays类的copyOf()实现数组复制

来源:互联网 发布:网络防御系统 编辑:程序博客网 时间:2024/05/29 06:43

                                       用System.arraycopy实现数组之间的复制以及Arrays类的copyOf()实现数组复制

一、System.arraycopy

         System提供了一个静态方法arraycopy(),可以使用它来实现数组之间的复制,其函数的原型是:

        

    public static native void arraycopy(Object src,  int  srcPos,                                        Object dest, int destPos,                                        int length);
      其中:

             src:源数组

             srcPos:源数组要复制的起始位置

             dest:目的数组

             destPos:目的数组放置的起始位置

             length:复制的长度

           注意:src and dest都必须是同类型或者可以进行转换类型的数组

      

      native关键字说明其修饰的方法是一个原生态方法,方法对应的实现不是在当前文件,而是在用其他语言(如C和C++)实现的文件中。Java语言本身不能对操作系统底层进行访问和操作,但是可以通过JNI接口调用其他语言来实现对底层的访问。

      JNI是Java本机接口(Java Native Interface),是一个本机编程接口,它是Java软件开发工具箱(Java Software Development Kit,SDK)的一部分。JNI允许Java代码使用以其他语言编写的代码和代码库。


      

package System;public class Arraycopy {public static void main(String args[]){int[] array = {1,2,3,4,5,6,7,8,9,10};System.arraycopy(array, 0, array, 5, 4);for(int i=0;i<array.length;i++){System.out.print(array[i]+"   ");}}}
 运行结果是

    1   2   3   4   5   1   2   3   4   10   


二、Arrays.copyOf()实现对数组的复制

    Arrays.copyOf()实现对数组的复制即不仅仅只是拷贝数组中的元素而是在拷贝元素时,会创建一个新的数组对象。而System.arrayCopy只拷贝已经存在数组元素

    其源码:

         

  public static int[] copyOf(int[] original, int newLength) {        int[] copy = new int[newLength];        System.arraycopy(original, 0, copy, 0,                         Math.min(original.length, newLength));        return copy;    }
    其中:original - 要复制的数组 

                newLength - 要返回的副本的长度 

   从上面的源码中可以看出先创建一个数组copy,然后调用System.arrayCopy把original中的内容复制到copy中,复制的长度为newLength,并返回copy数组

三、两者的区别

   1.代码示例

public class CopyTest {    public static void main(String args[]){        int[] array = {1,3,5,7,9} ;        int[] copyArray = new int[10];        System.arraycopy(array, 0, copyArray, 2, 5);        for(int i=0;i<copyArray.length;i++){            System.out.print(copyArray[i]+"   ");        }        System.out.println();        int[] newArray =  Arrays.copyOf(array, 10);        for(int i=0;i<newArray.length;i++){            System.out.print(newArray[i]+"   ");        }        System.out.println();        int[] newArray1 =  Arrays.copyOf(array, 2);        for(int i=0;i<newArray1.length;i++){            System.out.print(newArray1[i]+"   ");        }    }}

  运行结果:
     0   0   1   3   5   7   9   0   0   0   
     1   3   5   7   9   0   0   0   0   0   
     1   3 

2.两者的区别:

     1)System.arrayCopy需要目标数组,只是对两个数组的内容进行可能不完全的合并操作

     2)Arrays.copyOf()是复制数组至指定长度

0 0