Java 程式,將陣列元素左移


我們首先建立一個 int 陣列 −

int[] arr = { 10, 20, 30, 40, 50, 60, 70, 80, 90 };

現在,使用 arraycopy() 將陣列元素左移並正確放置元素,使其左移 −

System.arraycopy(arr, 1, arr, 0, arr.length - 1);

示例

 即時演示

import java.util.Arrays;
public class Demo {
   public static void main(String[] argv) throws Exception {
      int[] arr = { 10, 20, 30, 40, 50, 60, 70, 80, 90 };
      System.out.println("Initial array...
"+Arrays.toString(arr));       System.arraycopy(arr, 1, arr, 0, arr.length - 1);       System.out.println("Array after shifting to the left...");       System.out.println(Arrays.toString(arr));    } }

輸出

Initial array...
[10, 20, 30, 40, 50, 60, 70, 80, 90]
Array after shifting to the left...
[20, 30, 40, 50, 60, 70, 80, 90, 90]

更新於:30-7 月-2019

505 次瀏覽

開啟你的 事業

透過完成課程獲取認證

開始吧
廣告