Java 对数组扩容

源自JDK

int[] a = {1,2,3,4};

//
copyOf(T[] original, int newLength)
a = Arrays.copyOf(a, 8);

 

另附:

复制+转型 (Array.newInstance)

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;
}

 

posted @ 2020-10-29 19:33  Numerz  阅读(69)  评论(0编辑  收藏  举报