数组扩容和拷贝方法
本文主要介绍java提供的是数组拷贝和扩容方法。
Arrays.copyOf
原数组 = Arrays.copyOf(原数组,要扩容的长度 );
废话不多说,直接先上代码:
import java.util.Arrays;
public class ArrayCopy {
public static void main(String[] args) {
int[] arr = {1,2,3,4};
System.out.print("扩容前:");
for(int i :arr){
System.out.print(i+" ");
}
arr = Arrays.copyOf(arr,10);//将新数组,容量扩容为10
System.out.print("\n扩容后:");
for(int i :arr){
System.out.print(i+" ");
}
System.out.print("\n化身2System.copyOF:");
int[] srr = new int[20];
}
}
}
运行结果:
从输出结果就可以看出扩容前和扩容后是不一样的。
Arrays.copyOfRange()
原数组 = Arrays.copyOfRange(原数组,开始的位置,扩容长度);
废话不多说看代码:
import java.util.Arrays;
public class ArrayCopy {
public static void main(String[] args) {
int[] arr = {1,2,3,4};
System.out.print("扩容前:");
for(int i :arr){
System.out.print(i+" ");
}
arr = Arrays.copyOfRange(arr,1,11);
System.out.print("\n扩容且从指定位置开始后:");
for(int i :arr){
System.out.print(i+" ");
}
}
}
运行结果:
简单粗暴一下解决所有烦恼,妈妈再也不用为数组不够用担心了。
System.arraycopy();
System.arraycopy(原数组,原数组中开始拷贝的位置(int类型),新数组,拷贝的新数组的目标为位置(int类型));
直接上代码:
public class ArrayCopy {
public static void main(String[] args) {
int[] arr = {1,2,3,4};
System.out.print("原数组:");
for(int i :arr){
System.out.print(i+" ");
}
System.out.print("\n拷贝到新数组后:");
int[] srr = new int[20];
System.arraycopy(arr,1,srr,6,3);
for(int i :srr){
System.out.print(i+" ");
}
}
}
运行结果如下:
方便快捷~