所以我还是刚接触Java并且我一直在使用ArrayList - 我想要实现的是一种方法来做这样的事情:
Item 1
Item 2
Item 3
Item 4
Run Code Online (Sandbox Code Playgroud)
所以我试图能够在列表中移动项目,除非它已经在顶部,在这种情况下它将保持不变.例如,如果移动了第3项,则列表将为:
Item 1
Item 3
Item 2
Item 4
Run Code Online (Sandbox Code Playgroud)
从我目前的小理解那时起,我想要的是:
IF arrayname index is not equal to 0
THEN move up
ELSE do nothing
Run Code Online (Sandbox Code Playgroud)
我正在努力的部分是"向上移动"部分.任何有关如何实现这一目标的提示或代码示例都非常感谢.
Mik*_*kel 125
我在寻找答案时遇到了这个老问题,我想我会发布我找到的解决方案,以防其他人经过这里寻找同样的问题.
对于交换2个元素,Collections.swap很好.但是如果我们想要移动更多的元素,那么有一个更好的解决方案,包括创建性地使用Collections.sublist和Collections.rotate,直到我在这里看到它之前我才想到它:
这是一个引用,但去那里也为自己阅读整个事情:
请注意,此方法可以有用地应用于子列表以移动列表中的一个或多个元素,同时保留其余元素的顺序.例如,以下习语将索引j处的元素向前移动到位置k(必须大于或等于j):
Collections.rotate(list.subList(j, k+1), -1);
Str*_*ior 63
简单的交换对于在ArrayList中"移动某些东西"要好得多:
if(i > 0) {
Item toMove = arrayList.get(i);
arrayList.set(i, arrayList.get(i-1));
arrayList.set(i-1, toMove);
}
Run Code Online (Sandbox Code Playgroud)
因为ArrayList使用数组,如果从ArrayList中删除一个项目,它必须向上"移动"该项后面的所有元素以填充数组中的间隙.如果您插入一个项目,它必须移动该项目后的所有元素以腾出空间来插入它.如果您的阵列非常大,这些转变会变得非常昂贵.由于您知道要在列表中使用相同数量的元素,因此执行此类交换可以非常有效地将元素"移动"到列表中的其他位置.
正如Chris Buckler和Michal Kreuzman指出的那样,Collections类中甚至还有一个方便的方法可以将这三行代码减少为一行:
Collections.swap(arrayList, i, i-1);
Run Code Online (Sandbox Code Playgroud)
mic*_*man 29
你可以尝试这个简单的代码,Collections.swap(list,i,j)就是你要找的.
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
String toMoveUp = "3";
while (list.indexOf(toMoveUp) != 0) {
int i = list.indexOf(toMoveUp);
Collections.swap(list, i, i - 1);
}
System.out.println(list);
Run Code Online (Sandbox Code Playgroud)
Amo*_*are 22
要向上移动,请删除然后添加.
删除 - ArrayList.remove并将返回的对象分配给变量
然后将此对象添加回所需的索引 -ArrayList.add(int index, E element)
http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html#add(int,E)
正如Mikkel在Collections.rotate之前发布的那样,它是一种简单的方法。我正在使用这种方法在列表中上下移动项目。
public static <T> void moveItem(int sourceIndex, int targetIndex, List<T> list) {
if (sourceIndex <= targetIndex) {
Collections.rotate(list.subList(sourceIndex, targetIndex + 1), -1);
} else {
Collections.rotate(list.subList(targetIndex, sourceIndex + 1), 1);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
将递归应用于数组列表中的项的重新排序
public class ArrayListUtils {
public static <T> void reArrange(List<T> list,int from, int to){
if(from != to){
if(from > to)
reArrange(list,from -1, to);
else
reArrange(list,from +1, to);
Collections.swap(list, from, to);
}
}
}
Run Code Online (Sandbox Code Playgroud)
要Move在列表中添加项目,只需添加:
// move item to index 0
Object object = ObjectList.get(index);
ObjectList.remove(index);
ObjectList.add(0,object);
Run Code Online (Sandbox Code Playgroud)
要Swap在列表中的两个项目只需添加:
// swap item 10 with 20
Collections.swap(ObjectList,10,20);
Run Code Online (Sandbox Code Playgroud)