您的位置 首页 java

1分钟学习Java中数组快速复制

1分钟学习Java中数组快速复制

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 <U> the class of the  Object s in the original array
 * @param <T> 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,U> 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 <U> the class of the objects in the original array
 * @param <T> 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,U> 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数组的快速复制。你学会了吗?

文章来源:智云一二三科技

文章标题:1分钟学习Java中数组快速复制

文章地址:https://www.zhihuclub.com/197088.shtml

关于作者: 智云科技

热门文章

网站地图