SvS*_*SvS -3 java indexing list
想象一下,由索引(1-5)指定的Java中的List <1,2,3,4,5>.
如果我想将索引2(2)上的项目移动到索引4并将列表重新排列为<1,3,4,2,5>.
是否有一个简单的方法/收集框架来实现这个?LinkedList似乎是一个解决方案.
List<Integer> list = new ArrayList<>(List.of(1, 2, 3, 4));
Collections.swap(list, 1,3); // will swap the elements at the specified positions
Run Code Online (Sandbox Code Playgroud)
如果您只想将元素移动到某个位置,请尝试:
list.add(2, list.remove(0)); // move the item from index 0 to index 2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60 次 |
| 最近记录: |