java中数组扩容的三种方式
/**
* 数组扩容
*/
public class ArrayKR {
public static void main(String[] args) {
test01();
test02();
test03();
}
/**
* 方法一:
* 1.新建一个长度是原来数组两倍的数组
* 2.通过for循环将旧数组中的元素取出并拷贝到新数组中
*/
public static void test01(){
// 初始化数组
int[] a={33,55,666,78};
// 新建一个数组长度为原来的两倍
int[] b=new int[a.length*2];
// 将旧数组中的数据赋值给新数组
for(int i=0;i<a.length;i++){
b[i]=a[i];
}
System.out.println("test01原数组:" + Arrays.toString(a));
System.out.println("test01扩容后的数组:" + Arrays.toString(b));
}
/**
*方法二:使用Arrays.copyOf(array,to_index)
*/
public static void test02(){
/**
* Arrays.copyOf(array,to_index): 返回一个新的数组 可以指定新数组的长度
* array :原数组
* to_index:指定的数组长度
*
* 源码:
* public static int[] copyOf(int[] original, int newLength) {
* int[] copy = new int[newLength];
* System.arraycopy(original, 0, copy, 0,
* Math.min(original.length, newLength));
* return copy;
* }
* 从上面的源码中可以看出Arrays.copyOf(array,to_index) 底层是调用了System.arraycopy()方法
* 而System.arraycopy()方法本质上是一个数组拷贝的方法 将源数组中的元素按指定的复制长度拷贝到目的数组中
*
* public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
* src:源数组
* srcPos:源数组要复制的起始位置
* dest:目的数组
* destPos: 目的数组放置的起始位置
* length:复制长度(复制元素的个数)
*/
int[] a={333,555,666,888};
int[] b= Arrays.copyOf(a,a.length*2);
System.out.println("test02原数组:" + Arrays.toString(a));
System.out.println("test02扩容后的数组:" + Arrays.toString(b));
}
/**
* 方法三:使用System.arraycopy()方法
*/
public static void test03(){
// 初始化数组
int[] a={12,23,45,56,67};
// 创建新数组,长度是源数组的两倍
int[] b= new int[a.length*2];
// 将原数组中的元素拷贝到新数组中
System.arraycopy(a,0,b,0,a.length);
System.out.println("test03原数组:" + Arrays.toString(a));
System.out.println("test03扩容后的数组:" + Arrays.toString(b));
}
/**
* 小结:从上面三个方法中,可以看出数组扩容的思路是:
* 1,先创建一个指定长度的新数组
* 2. 将源数组中的元素拷贝到新数组中
*
*
* 方法二和方法三实际上都是通过调用System.arraycopy()方法来实现数组的拷贝功能的
* 方法三是直接调用System.arraycopy()方法,相对来说效率应该会更高一点
*
*/
}