Reputation: 1601
I read the documentation on this, and I'm not totally clear. I've zeroed in on the set method and I'm thinking that I would do reordering like this:
list.set(0,myObj);//Move first
list.set(list.indexOf(myObj) - 1, myObj);//Move up
list.set(list.indexOf(myObj) + 1, myObj);//Move down
list.set(list.size() - 1, myObj);//Move last
The documentation at http://developer.android.com/reference/java/util/List.html states that set returns the object that is displaced. So that leads me to think that I then have to re-place that object. Am I correct? So after a set operation as I described I would have two references to the object in the list. This would mean I'd have to loop down the list to place all the other object appropriately?
Upvotes: 3
Views: 222
Reputation: 109237
Use Collection class's swap()
for it
swap(List list, int i, int j)
Swaps the elements at the specified positions in the specified list.
Example:
Collections.swap(arrayList,0,4);
Upvotes: 5
Reputation: 16082
Look at Collections class to make things like reverse, reorder, sort etc.
You're looking probably for rotate or swap.
Upvotes: 2
Reputation: 46209
Yes, the element is replaced. It is easily fixed though:
int index = list.indexOf(myObj);
list.set(index, list.set(index - 1, myObj)); //Move up
This will switch list(index - 1)
with list(index)
. The other operations can be implemented in the same way.
Upvotes: 1
Reputation: 2632
Sound like you want to insert an object at the top o' the list. Don't use set.
It will bump the rest down.
Upvotes: 2