我有一个对象列表,我想在列表上做一些操作,这样一个特定的对象应该被移动到列表位置 0,位置 0 的对象将发生移动的对象。示意图如下。
名单如下
final List<Object> list= new ArrayList<Object>();
目前我已经制作了两个临时列表作为
final List<Object> temp1= new ArrayList<Object>();
final List<Object> temp2= new ArrayList<Object>();
为了执行该操作,我正在运行一个循环,并在特定条件下将对象添加到 temp1,否则添加到 temp2,如下所示:
for (int i = 0; i < 5; i++) {
if (i==3) {
temp1.add(i);
} else {
temp2.add(i);
}
}
最后做
list.addAll(temp1);
list.addAll(temp2);
如何在冗余和有效的步骤中执行相同的逻辑而不是使用临时列表。
最佳答案
使用这个 swap方法:
Collections.swap(List<?> list, int i, int j);
关于java - 交换列表的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27836533/