Problem Statement: Write a Java program to swap the positions of two elements in an ArrayList given their indices.
Here’s a Java program that demonstrates how to swap the positions of two elements in an ArrayList given their indices.
package com.javacodepoint.collection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SwapElementsInArrayListDemo {
public static void main(String[] args) {
ArrayList<String> elements = new ArrayList<>();
elements.add("Apple");
elements.add("Banana");
elements.add("Cherry");
elements.add("Date");
elements.add("Fig");
System.out.println("Original List: " + elements);
int index1 = 1;
int index2 = 3;
// Swapping elements at index1 and index2
swapElements(elements, index1, index2);
System.out
.println("List after swapping elements at index " + index1 + " and index " + index2 + ": " + elements);
}
// Method to swap elements in an ArrayList given their indices
public static <T> void swapElements(List<T> list, int index1, int index2) {
if (index1 < 0 || index1 >= list.size() || index2 < 0 || index2 >= list.size()) {
throw new IndexOutOfBoundsException("Invalid index");
}
Collections.swap(list, index1, index2);
}
}
OUTPUT:
Original List: [Apple, Banana, Cherry, Date, Fig]
List after swapping elements at index 1 and index 3: [Apple, Date, Cherry, Banana, Fig]
Explanation:
- Creating the List: We create an
ArrayListnamedelementsand populate it with some strings. - Printing the Original List: We print the contents of the
elementslist usingSystem.out.println(). - Defining Indices: We specify the indices (
index1andindex2) of the elements that we want to swap. - Swapping the Elements: We call the
swapElements()method to swap the elements at the specified indices. swapElements()Method: This method takes three parameters: the list (list), and the indices (index1andindex2) of the elements to be swapped.- Input Validation: Inside the method, we perform input validation to ensure that both
index1andindex2are valid indices within the bounds of the list. If any of these conditions are not met, anIndexOutOfBoundsExceptionis thrown. - Swapping Elements: We use the
Collections.swap()method to swap the elements in thelistat the specified indices. This method efficiently swaps the elements without the need for temporary variables. - Printing the Result List: Finally, we print the contents of the
elementslist after swapping the elements at the specified indices.
By using the Collections.swap() method, the program effectively swaps the positions of two elements in the ArrayList given their indices.
See also: Find a unique string in ArrayList with its frequency.
