在寫程序的過程中,我們常常會碰見數組空間不夠用的情況,比如我已經初始化了一個數組int []a = {1,2,3,4,5,6,7,8,9,10} ;這時,我想往數組下標3的位置插入一個元素,該怎麼做?用C語言實現太難了吧,需要調用memcpy函數要一個一個偏,但是在java中就不用那麼麻煩了,有種叫數組的擴容方式,輕鬆實現。來看看代碼:
public class HelloWorld { public static void main(String[] args){ // Scanner s = new Scanner(System.in); // System.out.println("請輸入一個數字"); // int num = s.nextInt(); //這個數組下標只能到9 int []a = {1,2,3,4,5,6,7,8,9,10}; //先擴容int []b = Getarray(a,3,100); Demoe.PrintArray(b); } //案例:有一個數組已經初始化完畢,現向其下標3插入一個元素100 public static int[] Getarray(int []a , int index , int num){ int src_array_length = a.length ; int []b = new int[src_array_length+1] ; for(int i = 0 ; i < a.length ; i++){ b[i] = a[i] ; } a = b ; //如果還想使用a,使得a指向b //接下來從最後一個元素開始,將最後一個元素的前面一個元素拷貝到最後一個//以此類推for(int i = a.length - 1 ; i > index ; i--){ a[i] = a[i-1]; } //別忘了,將要插入的元素插入到對應的數組坐標a[index] = num ; return a ; } }也可以使用java中的庫函數來實現
import java.util.Arrays; public class HelloWorld { public static void main(String[] args){ // Scanner s = new Scanner(System.in); // System.out.println("請輸入一個數字"); // int num = s.nextInt(); int []a = {1,2,3,4,5}; int []b = new int[a.length] ; //1、源數組//2、源數組的哪個位置開始//3、目標數組//4、目標數組的哪個位置開始存放//5、拷貝幾個//System.arraycopy(a, 0, b, 0, a.length); //Demoe.PrintArray(b); //擴容--->擴容了一倍//a = Arrays.copyOf(a, 2*a.length) ; //Demoe.PrintArray(a); a = insertArray(a , 3 , 100) ; //打印數組System.out.println(Arrays.toString(a)); } //寫一個函數,向整數數組的任意pos位置插入一個元素value public static int[] insertArray(int []a , int pos , int value){ if(pos < 0 || pos > a.length + 1) //索引下標不對,直接返回源數組return a ; //放入一個元素,先擴容,後復制a = Arrays.copyOf(a, a.length+1) ; for(int i = a.length - 1 ; i > pos ; i--){ a[i] = a[i-1] ; //後移動} a[pos] = value ; return a ; } }運行結果:
[1, 2, 3, 100, 4, 5]
總結
以上就是本文關於Java數組擴容實例代碼的全部內容,希望對大家有所幫助。如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!