注意学习(转载)出处:大佬博客
1、手动实现单一类型的数组扩容
public class test {
public static void main(String[] args) {
int[] arr= {1,2,3,4,5};
int[] newArray = new int[20];
for(int i = 0; i < arr.length; i++){
newArray[i] = arr[i];
}
System.out.println(Arrays.toString(newArray));
}
}
2、System.arraycopy() 方法实现数组扩容
System.arraycopy(原数组名,起始下标,新数组名,起始下标,复制长度);
public class test2 {
public static void main(String[] args) {
String[] names = new String[] { "A", "B", "C" };
String[] extended = new String[5];
extended[3] = "D";
extended[4] = "E";
System.arraycopy(names, 0, extended, 0, names.length);
for (String str : extended){
System.out.println(str);
}
}
}
3、扩展已经填满的数组方法 Arrays.copyOf()
public class test3 {
public static void main(String[] args) {
int[] a = {1,2,3,4,5};
a = Arrays.copyOf(a, 2 * a.length);
System.out.println(Arrays.toString(a));
}
}
4.利用反射实现方法 Arrays.copyOf()
思路:
首先获得 a 数组的类对象
确认它是一个数组
使用 Class类(只能定义表示数组的类对象)的 getComponentType 方法确定数组对应的类型。
实现代码:
/**
* 此方法通过分配相同类型的新数组并复制所有元素来增大数组。
* @param a 一个成长的数组。这可以是对象数组或基本类型数组
* @param newLength 新数组的长度
* @return 包含a的所有元素的较大数组。
*/
public class test4 {
public static Object goodCopyOf(Object a,int newLength){
Class extends Object> 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 void main(String[] args) {
int[] a= {1,2,3,4,5};
int[] res = (int[])goodCopyOf(a,10);
System.out.println(res.length);
}
}
5.newInstance 方法解析
public static Object newInstance(类> componentType, int length) throws NegativeArraySizeException
创建具有指定组件类型和长度的新数组。 调用此方法等效于创建数组,如下所示:
int[] x = {length};
Array.newInstance(componentType, x);
实例:
public class text5 {
public static void main(String[] args) {
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]
}
}
学习(转载)出处:大佬博客