Java Collections swap() Method

The swap() method in Java is a utility method provided by the java.util.Collections class. It is used to swap the elements at two specified positions in a given list. This method is useful when you need to rearrange elements within a list, such as during sorting algorithms or when implementing custom data manipulation logic.

Table of Contents

  1. Introduction
  2. swap() Method Syntax
  3. Examples
    • Basic Usage of swap()
    • Using swap() with Custom Classes
  4. Real-World Use Case
  5. Conclusion

Introduction

The Collections.swap() method provides a simple way to interchange the positions of two elements in a list. This operation modifies the list in place, meaning that the original list is directly altered. The method is commonly used in sorting algorithms, data shuffling, and other scenarios where element reordering is required.

swap() Method Syntax

The syntax for the swap() method is as follows:

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

Parameters:

  • list: The list in which the elements will be swapped.
  • i: The index of the first element to be swapped.
  • j: The index of the second element to be swapped.

Throws:

  • IndexOutOfBoundsException if either i or j is out of range (i.e., i < 0, i >= list.size(), j < 0, or j >= list.size()).
  • UnsupportedOperationException if the list does not support the set operation.
  • NullPointerException if the specified list is null.

Examples

Basic Usage of swap()

The following example demonstrates how to use the swap() method to interchange elements in a list of strings.

Example

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SwapExample {
    public static void main(String[] args) {
        // Create a list with initial elements
        List<String> fruits = new ArrayList<>();
        Collections.addAll(fruits, "Apple", "Banana", "Cherry", "Date");

        // Display the original list
        System.out.println("Original List: " + fruits);

        // Swap the elements at index 1 and index 3
        Collections.swap(fruits, 1, 3);

        // Display the list after swapping
        System.out.println("List after swap: " + fruits);
    }
}

Output:

Original List: [Apple, Banana, Cherry, Date]
List after swap: [Apple, Date, Cherry, Banana]

Using swap() with Custom Classes

You can also use the swap() method with lists containing instances of custom classes.

Example

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Student {
    String name;

    Student(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}

public class CustomSwapExample {
    public static void main(String[] args) {
        // Create a list of students
        List<Student> students = new ArrayList<>();
        students.add(new Student("Amit"));
        students.add(new Student("Neha"));
        students.add(new Student("Raj"));

        // Display the original student list
        System.out.println("Original Student List: " + students);

        // Swap the elements at index 0 and index 2
        Collections.swap(students, 0, 2);

        // Display the list after swapping
        System.out.println("Student List after swap: " + students);
    }
}

Output:

Original Student List: [Amit, Neha, Raj]
Student List after swap: [Raj, Neha, Amit]

Explanation:

  1. Original Order: The list is displayed in its original order before swapping.

  2. Swapping Elements: The swap() method is used to interchange the positions of elements at specified indices, modifying the list in place.

  3. Custom Class: The method works with custom class instances, allowing you to swap objects in a list of user-defined objects.

Real-World Use Case

Implementing a Simple Sorting Algorithm

In real-world applications, the swap() method can be used in sorting algorithms such as bubble sort or selection sort, where swapping elements is a fundamental operation.

Example

Imagine a scenario where you need to implement a simple bubble sort algorithm to sort a list of integers.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class BubbleSortExample {
    public static void main(String[] args) {
        // Create a list of integers
        List<Integer> numbers = new ArrayList<>();
        Collections.addAll(numbers, 5, 2, 8, 1, 3);

        // Display the original list
        System.out.println("Original List: " + numbers);

        // Perform bubble sort using the swap() method
        bubbleSort(numbers);

        // Display the sorted list
        System.out.println("Sorted List: " + numbers);
    }

    public static void bubbleSort(List<Integer> list) {
        int n = list.size();
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (list.get(j) > list.get(j + 1)) {
                    // Swap elements at j and j+1
                    Collections.swap(list, j, j + 1);
                }
            }
        }
    }
}

Output:

Original List: [5, 2, 8, 1, 3]
Sorted List: [1, 2, 3, 5, 8]

Explanation:

  1. Bubble Sort: The bubbleSort() method sorts the list using the bubble sort algorithm, which involves swapping adjacent elements that are out of order.

  2. Swapping in Sorting: The swap() method is used to interchange the positions of elements during the sorting process, illustrating its role in sorting algorithms.

Conclusion

The Collections.swap() method is a powerful utility for swapping elements in a list in Java. By providing a simple way to interchange element positions, it enhances the flexibility and readability of your code. This method is particularly valuable in scenarios where you need to rearrange list elements, such as in sorting algorithms, data shuffling, and custom data manipulation, improving the robustness and maintainability of your Java applications.

Leave a Comment

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

Scroll to Top