Java程式,將陣列元素向右移動
首先,讓我們建立一個 int 陣列 −
int[] arr = { 10, 20, 30, 40, 50, 60, 70, 80, 90 };
現在,使用 arraycopy() 將陣列元素向右移動並正確放置元素,以便其向右移動 −
System.arraycopy(arr, 0, arr, 1, 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, 0, arr, 1, arr.length - 1); System.out.println("Array after shifting to the right..."); System.out.println(Arrays.toString(arr)); } }
輸出
Initial array... [10, 20, 30, 40, 50, 60, 70, 80, 90] Array after shifting to the right... [10, 10, 20, 30, 40, 50, 60, 70, 80]
廣告