Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java (Android) re-ordering an object list

Tags:

java

android

list

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?

like image 460
Geeks On Hugs Avatar asked Nov 29 '25 10:11

Geeks On Hugs


1 Answers

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);
like image 106
user370305 Avatar answered Dec 01 '25 23:12

user370305