• Arrays.copyof(···)与System.arraycopy(···)区别


    首先观察先System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)的声明:

    [java] view plain copy
     
    1. public static native void arraycopy(Object src,  int  srcPos,  
    2.                                         Object dest, int destPos,  
    3.                                         int length);  

    src - 源数组。 
    srcPos - 源数组中的起始位置。 
    dest - 目标数组。 
    destPos - 目标数据中的起始位置。 
    length - 要复制的数组元素的数量。 
    该方法是用了native关键字,调用的为C++编写的底层函数,可见其为JDK中的底层函数。 
    再来看看Arrays.copyOf();该方法对于不同的数据类型都有相应的方法重载。 

    [java] view plain copy
     
    1. //复杂数据类型  
    2. public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {  
    3.         T[] copy = ((Object)newType == (Object)Object[].class)  
    4.             ? (T[]) new Object[newLength]  
    5.             : (T[]) Array.newInstance(newType.getComponentType(), newLength);  
    6.         System.arraycopy(original, 0, copy, 0,  
    7.                          Math.min(original.length, newLength));  
    8.         return copy;  
    9.     }  
    10. public static <T> T[] copyOf(T[] original, int newLength) {  
    11.     return (T[]) copyOf(original, newLength, original.getClass());  
    12. }  

    由U类型复制为T类型?
    original - 要复制的数组 
    newLength - 要返回的副本的长度 
    newType - 要返回的副本的类型

    [java] view plain copy
     
    1. //基本数据类型(其他类似byte,short···)  
    2. public static int[] copyOf(int[] original, int newLength) {  
    3.         int[] copy = new int[newLength];  
    4.         System.arraycopy(original, 0, copy, 0,  
    5.                          Math.min(original.length, newLength));  
    6.         return copy;  
    7.     }  

    观察其源代码发现copyOf(),在其内部创建了一个新的数组,然后调用arrayCopy()向其复制内容,返回出去。 
    总结: 
    1.copyOf()的实现是用的是arrayCopy(); 
    2.arrayCopy()需要目标数组,对两个数组的内容进行可能不完全的合并操作。 
    3.copyOf()在内部新建一个数组,调用arrayCopy()将original内容复制到copy中去,并且长度为newLength。返回copy; 

  • 相关阅读:
    MathType编辑半直积符号的步骤
    用几何画板演示涡旋电场的方法
    MathType编辑双向斜箭头的教程
    最实用的几何画板绘图技巧大总结
    怎么让Word编辑公式又快又好
    在几何画板中作三角形高的方法
    MathType中输入破折号的教程
    几何画板5.06最强中文版破解-下载-注册码
    如何通过几何画板来验证海伦公式
    如何用公式编辑器编辑直角三角形符号
  • 原文地址:https://www.cnblogs.com/liujinhong/p/6513322.html
Copyright © 2020-2023  润新知