60.4k views
8 votes
Make a String ArrayList.Then write a Java method that swaps the first and last elements.

User Gerd
by
4.3k points

1 Answer

0 votes

Answer: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.

Declaration −The java.util.Collections.swap() method is declared as follows

public static void swap(List <?> list, int i, int j)

where i is the index of the first element to be swapped, j is the index of the other element to be swapped and list is the list where the swapping takes place.

Step-by-step explanation:

import java.util.*;

public class Example {

public static void main (String[] args) {

ArrayList<Integer> list = new ArrayList<Integer>();

list.add(10);//0

list.add(20);//1

list.add(30);//2

list.add(40);//3

list.add(50);//4

System.out.println("Original list : " + list);

Collections.swap(list, 4, 0); // swapping element at index 3 i.e. 50 and index 1 i.e. 10

System.out.println("List after swapping : " + list);

}

}

User Pritam Chaudhari
by
4.4k points