Android: ArrayList Move item to position 0

I have an ArrayList , and I need to make sure that the specific element is at position 0, and if not, I need to move it there. The element has an isStartItem boolean on it, so I can easily find the specific element that should be at position 0, but how can I move it to the right position?

I assume I need to use something like this:

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

But this does not seem to work ...

+4
source share
4 answers

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

Edit -

 Collection.swap(myArray, i, 0); 

for this -

 Collections.swap(myArray, i, 0); 

Take a look at this example.

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

+16
source

I don't know what Collection.swap , 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 for a long time:

 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; } } 
+5
source

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

1. Swap items

Collections.swap (myArray, i, 0);

→ Here, the ā€œiā€ position will be moved to the 0th position, and all other elements in this range will remain as they are.

2. Move items

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

→ Here the item at position ā€œiā€ will be deleted and added to the 0th position. Here, all other positions will be shifted when adding a new element to 0.

Hope this helps you understand the difference between swap and position offset. Use the solution according to your requirements.

0
source

You can use the set function from Arraylist.

 set(position,object) 
-1
source

All Articles