我们在使用数组时,如果设置长了,短了都不太合适,甚至还需要在运行时(或者事先已经定义了长度)改变一个定长数组的大小。
在以下的代码中给出注释,请参看!一、定义一个新的数组
在以下的代码中给出注释,请参看!一、定义一个新的数组
int [] a = {1, 2, 3, 4, 5};
//假设此时需要改变这个数组大小。
//1.可以设置一个新的数组存放它的数据 ,长度增加为你想要的。
int [] b = new int[6];
b[5] = 6;
System.arraycopy(a, 0, b, 0, a.length);//数组a从0 开始 赋值到b 从0开始,长度为:?
for(int t : b){
System.out.println(t);
}
二、利用ArrayList 、Vector之类的可以动态描述的,如果有需要可以转换成数组类型进行之后的操作。(可以事先就定义这样的数据类型,添加数据进行操作,然后转换成数组。)
List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i< a.length; i ++){
list.add(a[i]);
}
list.add(6);
// for(Integer l : list){// 直接在list中输出。
// System.out.println(l);
// }
Integer array [] = list.toArray(new Integer[0]);
// Object[] arr = list.toArray(new Objec