Swap two elements in ArrayList

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:

  1. Creating the List: We create an ArrayList named elements and populate it with some strings.
  2. Printing the Original List: We print the contents of the elements list using System.out.println().
  3. Defining Indices: We specify the indices (index1 and index2) of the elements that we want to swap.
  4. Swapping the Elements: We call the swapElements() method to swap the elements at the specified indices.
  5. swapElements() Method: This method takes three parameters: the list (list), and the indices (index1 and index2) of the elements to be swapped.
  6. Input Validation: Inside the method, we perform input validation to ensure that both index1 and index2 are valid indices within the bounds of the list. If any of these conditions are not met, an IndexOutOfBoundsException is thrown.
  7. Swapping Elements: We use the Collections.swap() method to swap the elements in the list at the specified indices. This method efficiently swaps the elements without the need for temporary variables.
  8. Printing the Result List: Finally, we print the contents of the elements list 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.

Java logical programs list


Java Basic Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *