
Java System类提供了的arraycopy快速复制数组方法。具体函数如下:
public class ArrayCopyTest { public static void main(String[] args) { int[] arr = {1, 2, 3}; int[] destArr = new int[arr.length]; System.arraycopy(arr, 0, destArr, 0, arr.length); }}example:
/** * @param the class of the objects in the original array * @param the class of the objects in the returned array * @param original the array to be copied * @param newLength the length of the copy to be returned * @param newType the class of the copy to be returned * @return a copy of the original array, truncated or padded with nulls * to obtain the specified length */ public static T[] copyOf(U[] original, int newLength, Class extends T[]> newType) { @SuppressWarnings("unchecked") T[] copy = ((Object)newType == (Object)Object[].class) ? (T[]) new Object[newLength] : (T[]) Array.newInstance(newType.getComponentType(), newLength); System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } Java Arrays.copyOf()使用
/** * @param the class of the objects in the original array * @param the class of the objects in the returned array * @param original the array to be copied * @param newLength the length of the copy to be returned * @param newType the class of the copy to be returned * @return a copy of the original array, truncated or padded with nulls * to obtain the specified length */ public static T[] copyOf(U[] original, int newLength, Class extends T[]> newType) { @SuppressWarnings("unchecked") T[] copy = ((Object)newType == (Object)Object[].class) ? (T[]) new Object[newLength] : (T[]) Array.newInstance(newType.getComponentType(), newLength); System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } 以上就是Java数组的快速复制。你学会了吗?
本文介绍Java中使用System.arraycopy和Arrays.copyOf方法实现数组的快速复制。System.arraycopy能够高效地从源数组复制元素到目标数组;而Arrays.copyOf则可以创建并返回一个指定长度的新数组,新数组会包含原数组的部分或全部元素。
1540

被折叠的 条评论
为什么被折叠?



