Geeks On Hugs
Geeks On Hugs

Reputation: 1601

Java (Android) re-ordering an object 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?

Upvotes: 3

Views: 222

Answers (4)

user370305
user370305

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

pawelzieba
pawelzieba

Reputation: 16082

Look at Collections class to make things like reverse, reorder, sort etc.
You're looking probably for rotate or swap.

Upvotes: 2

Keppil
Keppil

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

Perry Tew
Perry Tew

Reputation: 2632

Sound like you want to insert an object at the top o' the list. Don't use set.

Use List.add(0, myObj)

It will bump the rest down.

Upvotes: 2

Related Questions