Java 实现数组扩容

1.手动实现单一类型数组扩容

int[] a= {1,2,3,4,5};
int[] newArray = new int[10];
for(int i = 0; i < a.length; i++){
	newArray[i] = a[i];
}
System.out.println(Arrays.toString(newArray));
//输出结果为[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]

2.System.arraycopy() 方法实现数组扩容

  • 实例:
int[] a= {1,2,3,4,5};
int[] newArray = new int[10];
System.arraycopy(a,0,newArray,0,a.length);
System.out.println(Arrays.toString(newArray));
//输出结果为[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
  • 函数 public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

    将指定源数组中的数组从指定位置开始复制到目标数组的指定位置。 阵列组件的一个子序列被从通过引用的源阵列复制src被引用的目标阵列dest 。 复制的组件数等于length参数。 在位置的部件srcPos通过srcPos+length-1源阵列中的被复制到的位置destPos通过destPos+length-1分别,目的地阵列。

  • 参数解释:

    • src 源数组
    • srcPos 源数组中的起始位置
    • dest 目标数组
    • destPos 目标数组中的起始位置
    • length 要复制的数组元素的数量
  • 注意:

    • 如果srcdest参数引用相同的数组对象,则执行复制,就好像位置srcPossrcPos+length-1的组件首次复制到具有length组件的临时数组,然后临时数组的内容被复制到位置destPos通过目标数组的destPos+length-1
    • 如果destnull ,则抛出NullPointerException
    • 如果srcnull ,则抛出NullPointerException并且不修改目标阵列。

3.扩展已经填满的数组方法 Arrays.copyOf()

int[] a = {1,2,3,4,5};
a = Arrays.copyOf(a, 2 * a.length);
System.out.println(Arrays.toString(a));
//输出结果为 [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]

4.利用反射实现方法 Arrays.copyOf()

  • 思路:

    1. 首先获得 a 数组的类对象
    2. 确认它是一个数组
    3. 使用 Class类(只能定义表示数组的类对象)的 getComponentType 方法确定数组对应的类型。
  • 实现代码:

    /**
     * 此方法通过分配相同类型的新数组并复制所有元素来增大数组。
     * @param a 一个成长的数组。这可以是对象数组或基本类型数组
     * @param newLength 新数组的长度
     * @return 包含a的所有元素的较大数组。
     */
    public static Object goodCopyOf(Object a,int newLength){
        Class cl = a.getClass();
        if(!cl.isArray()) return null;
        //返回表示数组的组件类型的类 。 如果此类不表示数组类,则此方法返回null。
        Class componentType = cl.getComponentType();
        int length = Array.getLength(a);
        //是 Array类中的静态方法 newInstance,它能够构造新数组。在调用它时必须提供两个参数,一个是数组的元素类型,一个是数组的长度。
        Object newArray = Array.newInstance(componentType,newLength);
        System.arraycopy(a,0,newArray,0,Math.min(length,newLength));
        return newArray;
    }
    

5.newInstance 方法解析

public static Object newInstance(类<?> componentType, int length) throws NegativeArraySizeException

创建具有指定组件类型和长度的新数组。 调用此方法等效于创建数组,如下所示:

int[] x = {length};
Array.newInstance(componentType, x);

实例:

int[] a= {1,2,3,4,5};
int[] newArray = (int[]) Array.newInstance(a.getClass().getComponentType(),10);
System.out.println(Arrays.toString(newArray));
//输出结果为[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
posted @ 2020-04-27 23:14  花染梦  阅读(2866)  评论(0编辑  收藏  举报