Collections.rotate() 是 Java 中高效原地循环移位 List 的工具方法:正数 distance 表示右移,负数表示左移,自动取模且要求可修改列表;支持子列表局部旋转及数组与 List 间正确转换。

Collections.rotate() 是 Java 中对 List 进行原地循环移位的高效工具方法,一行调用即可完成左移或右移,无需手写索引计算、临时数组或多次 add/remove。
方向与偏移量的实际含义
调用 Collections.rotate(list, distance) 时:
- distance > 0:向右循环移动 —— 末尾元素“绕到”前面,例如
[1,2,3,4,5]右移 2 位变为[4,5,1,2,3] - distance < 0:向左循环移动 —— 首部元素“移到”后面,例如左移 1 位得
[2,3,4,5,1] - distance 自动对列表长度取模,
rotate(list, 7)在 5 元素列表中等价于rotate(list, 2),不会越界或异常 - distance == 0 或 list.size() ≤ 1 时无任何变化
必须确保传入可修改的 List
该方法只接受支持结构修改的 List 实现:
- ✅ 推荐:直接使用
new ArrayList(...)或LinkedList - ⚠️ 注意:
Arrays.asList(arr)返回的是固定大小视图,虽部分 JDK 版本能运行 rotate,但严格来说不支持 add/remove;为安全起见,应包装为new ArrayList(Arrays.asList(...)) - ❌ 禁止:不可变列表(如
Collections.unmodifiableList())、原始类型数组(int[])不能直接传入
子列表旋转实现局部调整
借助 list.subList(from, to),可在不扰动其他元素的前提下移动局部片段:
立即学习“Java免费学习笔记(深入)”;
- 将索引 j 的元素前移至位置 k(k ≥ j):调用
Collections.rotate(list.subList(j, k + 1), -1) - 例如
[a,b,c,d,e]中把 b(索引 1)前移两位:执行rotate(subList(1, 4), -1)→[a,c,d,b,e] - 正数 distance 在子列表内表示“向后推”,负数表示“向前插”,灵活模拟剪切粘贴效果
数组 ↔ List 转换配合使用
若起点是普通数组,需注意类型适配:
- 对象数组(如
String[]):List<String> list = new ArrayList<>(Arrays.asList(arr)); - 基本类型数组(如
int[]):先装箱,List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList()); - 结果转回数组:
String[] result = list.toArray(new String[0]);或流式转换int[] back = list.stream().mapToInt(Integer::intValue).toArray();


















