关于java数组的扩容问题_java数组扩容题目问题

注意学习(转载)出处:大佬博客

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]

}

}

学习(转载)出处:大佬博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值