java将list集合中某个元素移到第一位,其他元素位置平移
时间: 2024-02-09 21:09:50 浏览: 31
可以使用 `Collections` 类中的 `rotate` 方法来实现将 `List` 集合中的某个元素移动到第一位,同时其他元素的位置向后平移。
下面是示例代码:
```java
import java.util.*;
public class ListRotateExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e"));
System.out.println("Original List: " + list);
int indexToMove = 3; // 将索引为 3 的元素移动到第一位
Collections.rotate(list.subList(0, indexToMove + 1), 1);
System.out.println("After rotating: " + list);
}
}
```
输出结果:
```
Original List: [a, b, c, d, e]
After rotating: [d, a, b, c, e]
```
在上面的示例代码中,我们将索引为 3 的元素(即 "d")移动到了第一位,其他元素的位置向后平移了一位。