How do I swap the the first and last elements of an ArrayList
? I know how to swap the elements of an array: setting a temporary value to store the first element, letting the first element equal the last element, then letting the last element equal the stored first element.
int a = values[0]; int n = values.length; values[0] = values[n-1]; values[n-1] = a;
So for an ArrayList<String>
would it be like this?
String a = words.get(0); int n = words.size(); words.get(0) = words.get(n-1); words.get(n-1) = a
In order to swap elements of ArrayList with Java collections, we need to use the Collections. swap() method. It swaps the elements at the specified positions in the list.
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. We convert our firstArr into a list using Arrays. asList() and then pass it to the swap() method with positions 0 and 2 .
The standard solution to swap two elements in a List is using the Collections. swap() method, which swaps the elements at the specified positions in a list.
To reverse an ArrayList in java, one can use Collections class reverse method i.e Collections. reverse() method. Collections reverse method reverses the element of ArrayList in linear time i.e time complexity is O(n). Collections reverse method accepts a List type as an argument.
You can use Collections.swap(List<?> list, int i, int j);
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