在Java中,数组元素的移位可以通过多种方法实现,包括使用`System.arraycopy`方法、循环赋值等。下面是一些示例代码,展示了如何实现数组的右移和左移操作:
数组右移
import java.util.Arrays;public class ArrayShift {public static void main(String[] args) {int[] arr = {10, 20, 30, 40, 50, 60, 70, 80, 90};System.arraycopy(arr, 0, arr, 1, arr.length - 1);System.out.println("Array after shifting to the right...");System.out.println(Arrays.toString(arr));}}
数组左移
import java.util.Arrays;public class ArrayShift {public static void main(String[] args) {int[] arr = {10, 20, 30, 40, 50, 60, 70, 80, 90};System.arraycopy(arr, 1, arr, 0, arr.length - 1);System.out.println("Array after shifting to the left...");System.out.println(Arrays.toString(arr));}}

自定义移位函数
import java.util.Arrays;public class ArrayShift {public static void main(String[] args) {int[] arr = {10, 20, 30, 40, 50, 60, 70, 80, 90};shiftArray(arr, 2); // 向右移动2个位置System.out.println("Array after shifting to the right by 2 positions...");System.out.println(Arrays.toString(arr));shiftArray(arr, 2); // 向右移动2个位置System.out.println("Array after shifting to the right by 2 positions...");System.out.println(Arrays.toString(arr));}public static void shiftArray(int[] arr, int shift) {int n = arr.length;int[] temp = new int[n];for (int i = 0; i < n; i++) {temp[(i + shift) % n] = arr[i];}System.arraycopy(temp, 0, arr, 0, n);}}
以上代码展示了如何使用`System.arraycopy`方法进行数组的右移和左移,以及自定义一个函数`shiftArray`来实现数组的循环移位。你可以根据需要选择合适的方法进行操作
