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.
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With