Android: ArrayList Move Item to Position 0

随声附和 提交于 2019-11-30 10:05:14

You need to use Collections class's swap method. Collections, with an s at the end.

Change -

Collection.swap(myArray, i, 0);

to this -

Collections.swap(myArray, i, 0);

Take a look at this example.

Collection and Collections are two different things in Java. The first one is an interface, the second one is a class. The later one has a static swap method, but the former one doesn't.

I don't know what Collection.swap is, but this code should work:

for(int i=0; i<myArray.size(); i++){    
    if(myArray.get(i).isStartItem()){
        Collections.swap(myArray, i, 0);
        break;
    }
}

Or you can do it long-hand:

for(int i=0; i<myArray.size(); i++){    
    if(myArray.get(i).isStartItem()){
        Object thing = myArray.remove(i); // or whatever type is appropriate
        myArray.add(0, thing);
        break;
    }
}

There are 2 ways of moving an item to the desired position in the ArrayList.

1. Swap the items

Collections.swap(myArray, i, 0);

--> Here position "i" will be moved to 0th position and all the other items in between this range will remain as it is.

2. Shift the items

myArray.add(0,myArray.remove(i))

--> Here item at position "i" will be removed and added to the 0th position. Here all the other items position will be shifted as you're adding a new item at 0.

Hope this will helps you to understand the difference between swap and shift the position. Use the solution according to your requirement.

You can use the set function of Arraylist.

set(position,object)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!