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]
广告