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]
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
和dest
参数引用相同的数组对象,则执行复制,就好像位置srcPos
到srcPos+length-1
的组件首次复制到具有length
组件的临时数组,然后临时数组的内容被复制到位置destPos
通过目标数组的destPos+length-1
。dest
是null
,则抛出NullPointerException
。src
是null
,则抛出NullPointerException
并且不修改目标阵列。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]
思路:
a
数组的类对象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;
}
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]
原文:https://www.cnblogs.com/huaranmeng/p/12790983.html