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