當數組定義完成后,數組存儲元素的個數就確定了,因為在定義數組時,要指定數組的長度. 如果想要在數組中存儲更多的數據, 就需要對數組擴容。
package com.wkcto.chapter03.demo01;
import java.util.Arrays;
/**
* 數組擴容
* @author 蛙課網
*
*/
public class Test06 {
public static void main(String[] args) {
// m1(); //完全手動擴容
// m2(); //數組復制調用 了System.arraycopy(0方法
m3(); //調用 Arrays.copyOf(0實現擴容
}
private static void m3() {
// 定義長度為5的數組
int[] data = { 1, 2, 3, 4, 5 };
// 想要在數組中存儲更多的數據,需要對數組擴容
//Arrays工具類copyOf(源數組, 新數組的長度) 可以實現數組的擴容
data = Arrays.copyOf(data, data.length*3/2);
System.out.println( Arrays.toString(data));
}
private static void m2() {
//定義長度為5的數組
int [] data = {1,2,3,4,5};
//想要在數組中存儲更多的數據,需要對數組擴容
//(1) 定義一個更大的數組
int [] newData = new int[data.length * 3 / 2] ; //按1.5倍大小擴容
//(2)把原來數組的內容復制到新數組中
//把src數組從srcPos開始的length個元素復制到dest數組的destPos開始的位置
// System.arraycopy(src, srcPos, dest, destPos, length);
System.arraycopy(data, 0, newData, 0, data.length);
//arraycopy()方法使用了native修飾,沒有方法體, 該方法的方法體可能是由C/C++實現的
//JNI,Java native Interface技術,可以在Java語言中調用其他語言編寫的代碼
//(3) 讓原來的數組名指向新的數組
data = newData;
//
System.out.println( Arrays.toString(data));
}
private static void m1() {
//1)定義長度為5的數組
int [] data = {1,2,3,4,5};
//2)想要在數組中存儲更多的數據,需要對數組擴容
//(1) 定義一個更大的數組
int [] newData = new int[data.length * 3 / 2] ; //按1.5倍大小擴容
//(2)把原來數組的內容復制到新數組中
for( int i = 0 ; i < data.length; i++){
newData[i] = data[i];
}
//(3) 讓原來的數組名指向新的數組
data = newData;
//
System.out.println( Arrays.toString(data));
}
}