Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arraylist swap elements [duplicate]

Tags:

java

arraylist

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 
like image 800
qvd Avatar asked Apr 12 '13 05:04

qvd


People also ask

Can we swap elements ArrayList?

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.

How do you swap two values in an array Java?

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 .

How do you swap two elements?

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.

How do I print an ArrayList backwards?

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.


1 Answers

You can use Collections.swap(List<?> list, int i, int j);

like image 150
Evgeniy Dorofeev Avatar answered Oct 13 '22 19:10

Evgeniy Dorofeev