Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: ArrayList Move Item to Position 0

I have an ArrayList and I need to make sure a specific item is at the 0 position and if it is not, I need to move it there. The item has an isStartItem boolean on it, so I can easily find the specific item I need to be in position 0 but then how do I go about moving it to the right position?

I am assuming 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...

like image 293
ryandlf Avatar asked Aug 12 '11 04:08

ryandlf


2 Answers

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.

like image 139
MD Sayem Ahmed Avatar answered Oct 16 '22 14:10

MD Sayem Ahmed


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;
    }
}
like image 33
Ted Hopp Avatar answered Oct 16 '22 13:10

Ted Hopp