我想使用Collections.swap
上下移动自定义数组项,但我不明白如何以某种方式实现它,以便我的应用不会崩溃。
private List<Drinks> myDrinks = new ArrayList<Drinks>();
private ArrayList<String> yourItems;
...
private void populateDrinkList() {
if (yourItems.contains("pie")){
myDrinks.add(new Drinks("a"));
myDrinks.add(new Drinks("b"));
myDrinks.add(new Drinks("c"));
myDrinks.add(new Drinks("d"));
myDrinks.add(new Drinks("e"));
if (yourItems.contains("chocolate")){
String toMoveUp = "e";
while (myDrinks.indexOf(toMoveUp) != 0) {
int i = myDrinks.indexOf(toMoveUp);
Collections.swap(myDrinks, i, i - 1);
}
}
答案 0 :(得分:0)
首先修复yourItems
变量ArrayList
它应该以这种方式声明:
private ArrayList<String> yourItems=new ArrayList<String>();
第二点myDrinks
是一个ArrayList
集合,它将Drinks
Object作为参数,这意味着你不能使用String toMoveup来查看它,而应该是Drinks
对象:
Drinks toMoveUp=new Drinks("e");
然后:
while (myDrinks.indexOf(toMoveUp) != 0) {
int i = myDrinks.indexOf(toMoveUp);
Collections.swap(myDrinks, i, i - 1);
}
祝你好运
答案 1 :(得分:-1)
您可以从列表中删除它(给出您已经获得的索引),然后使用myDrinks.add(0,<Object>)
方法将其添加为第0个元素。代码是,
Drinks toMoveUp = new Drinks("e");
int index = myDrinks.indexOf(toMoveUp);
myDrinks.remove(index); //remove from where it is now
myDrinks.add(0,toMoveUp); //add to the top