Java提供了一个非常方便的字符串拷贝接口:System.arraycopy(), 很多容器(比如ArrayList, SimpleArrayMap)的的底层实现都能看到它的身影
1.原理:
其接口形式为:
public static native void arraycopy(Object var0, int var1, Object var2, int var3, int var4);
其中var0: 源数组
var1:拷贝数据时,源数组的起始下标.
var2:目的数组
var3:拷贝数据时,目的数组的起始下标.
var4:拷贝数据的长度.
其具体代码实现暂未找到,个人实现如下:
/** * This is used to copy a string from a source array to destination array. * @param source The source arrays. * @param sourcePoint The start index of the source arrays. * @param destination The destination arrays * @param destinationPoint The start index of the destination arrays. * @param length */ private static void arrayCopyDIY(int[] source, int sourcePoint, int[] destination, int destinationPoint, int length){ if (source == null || destination == null || length ==0) { return; } if (source.length <1 || destination.length <1){ return; } if (source.length < length || destination.length < length){ return; } for (int i = 0; i<length; i++){ destination[destinationPoint+i] = source[sourcePoint+i]; } }2.使用方法
public static void main(String[] args){ int[] sourceArray = new int[]{1,2,3,4,5,6}; int[] DestinationArray = new int[4]; System.out.println("Initial destinationArray="+ Arrays.toString(DestinationArray)); System.arraycopy(sourceArray, 2, DestinationArray, 0, 4); System.out.println("Final destinationArray="+ Arrays.toString(DestinationArray)); }输出: