Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to switch elements in an ArrayList

The following ArrayList populates a ArrayAdapter.

List<String> hold_people = new ArrayList<String>();

hold_people.add("Frank");
hold_people.add("Bob");
hold_people.add("Tom");
hold_people.add("Alice");
hold_people.add("Glen");

Frank is in the first spot. but the user wants to see Alice first. How do move Alice to the first spot ?

I can not sort it alphabetically because i must maintain a certain order... based on user request.

like image 500
user3134565 Avatar asked Mar 28 '14 17:03

user3134565


People also ask

How do you swap elements in an ArrayList?

We can swap two elements of Array List using Collections. swap() method. This method accepts three arguments. The first argument is the ArrayList and the other two arguments are the indices of the elements.

How do you switch elements in Java?

The swap() method of java. util. Collections class is used to swap the elements at the specified positions in the specified list. If the specified positions are equal, invoking this method leaves the list unchanged.

Can we swap elements in array?

In an array, we can swap variables from two different locations. There are innumerable ways to swap elements in an array. let's demonstrate a few ways of swapping elements. We introduce a new variable and let it hold one of the two array values(a) which are willing to swap.

How do you swap two values in an array Java?

Use Collections. swap() to Swap Two Elements of an Array in Java. The swap() method of the Collections class swaps elements at the specified position in the specified list.


1 Answers

You can use Collections.swap.

Collections.swap(hold_people, 0, hold_people.indexOf("Alice"));

This will swap the element that is first in the list with "Alice".

Be aware that hold_people.indexOf("Alice") can return -1 if you don't have the String "Alice" in your list, so you may check that the list contains it.

int index = hold_people.indexOf("Alice");
if(index != -1)
    Collections.swap(hold_people, 0, index);
like image 199
Alexis C. Avatar answered Sep 30 '22 02:09

Alexis C.