向上或向下移动自定义数组项

时间:2013-12-24 04:28:06

标签: java android arrays sorting

我想使用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);
    }
}

2 个答案:

答案 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