Creating a Swap Function

JavaJavaBeginner
Practice Now

Introduction

In Java, swapping primitive data types is easy and can be done with simple variable assignment. However, swapping non-primitive data types, like objects, can be complex. Fortunately, the java.util.Collections class includes a swap() method that makes it easy to swap elements in a list of primitive and non-primitive data types. In this lab, you will learn how to create a swap function using the Collections.swap() method.

Create a Java file

First, create a Java file named SwapFunction.java in the ~/project directory.

touch ~/project/SwapFunction.java

Import the java.util library

Import the java.util library to use the Collections class in the Java file.

import java.util.*;

Declare a function that accepts a list of any data type

Declare a function that will accept a list of any data type. You can specify the data type using Java's Generics feature. For this example, we will build a function named swapElements that takes an ArrayList of String objects and swaps two elements at specified indexes.

public class SwapFunction {
    public static <T> void swapElements(ArrayList<T> list, int index1, int index2){
        // swap code goes here
    }
}

Implement a swap function using the Collections.swap() method

In the swapElements function, use the Collections.swap() method to swap the elements at the specified indices.

public class SwapFunction {
    public static <T> void swapElements(ArrayList<T> list, int index1, int index2){
        Collections.swap(list, index1, index2);
    }
}

Test the swap function

Test the swapElements function by creating an ArrayList of String objects, adding some elements, and then swapping two elements.

public class SwapFunction {
    public static <T> void swapElements(ArrayList<T> list, int index1, int index2){
        Collections.swap(list, index1, index2);
    }

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "orange", "kiwi"));
        System.out.println("Before Swap: " + list);
        swapElements(list, 0, 2);
        System.out.println("After Swap: " + list);
    }
}

Save the Java file, then compile and run it.

javac ~/project/SwapFunction.java && java SwapFunction

You should see the following output:

Before Swap: [apple, banana, orange, kiwi]
After Swap: [orange, banana, apple, kiwi]

Swap multiple elements in a list

The swapElements function can also be used to swap multiple elements in a list by calling the Collections.swap() method multiple times.

public class SwapFunction {
    public static <T> void swapElements(ArrayList<T> list, int index1, int index2){
        Collections.swap(list, index1, index2);
    }

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "orange", "kiwi"));
        System.out.println("Before Swap: " + list);
        swapElements(list, 0, 3);
        swapElements(list, 1, 2);
        System.out.println("After Swap: " + list);
    }
}

Save the Java file, then compile and run it.

javac ~/project/SwapFunction.java && java SwapFunction

You should see the following output:

Before Swap: [apple, banana, orange, kiwi]
After Swap: [kiwi, orange, banana, apple]

Handle exceptions

If the specified indices are out of bounds for the list, the swapElements function will throw an IndexOutOfBoundsException exception. To handle this, add a try-catch block to the function.

public class SwapFunction {
    public static <T> void swapElements(ArrayList<T> list, int index1, int index2){
        try {
            Collections.swap(list, index1, index2);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "orange", "kiwi"));
        System.out.println("Before Swap: " + list);
        swapElements(list, 0, 4); // out of bounds index
        swapElements(list, 1, 2);
        System.out.println("After Swap: " + list);
    }
}

Save the Java file, then compile and run it.

javac ~/project/SwapFunction.java && java SwapFunction

You should see the following output:

Before Swap: [apple, banana, orange, kiwi]
Error: Index 4 out of bounds for length 4
After Swap: [apple, orange, banana, kiwi]

Swap elements in an array

You can also use the swapElements function to swap elements in an array by converting the array to a list.

public class SwapFunction {
    public static <T> void swapElements(ArrayList<T> list, int index1, int index2){
        try {
            Collections.swap(list, index1, index2);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        String[] array = {"apple", "banana", "orange", "kiwi"};
        ArrayList<String> list = new ArrayList<>(Arrays.asList(array));
        System.out.println("Before Swap: " + list);
        swapElements(list, 0, 3);
        swapElements(list, 1, 2);
        System.out.println("After Swap: " + list);
    }
}

Save the Java file, then compile and run it.

javac ~/project/SwapFunction.java && java SwapFunction

You should see the following output:

Before Swap: [apple, banana, orange, kiwi]
After Swap: [kiwi, orange, banana, apple]

Swap elements in a list of custom objects

The swapElements function can also be used to swap elements in a list of custom objects. Define a Person class with name and age fields, then create a list of Person objects, and swap two elements in the list.

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String toString() {
        return name + " (" + age + ")";
    }
}

public class SwapFunction {
    public static <T> void swapElements(ArrayList<T> list, int index1, int index2){
        try {
            Collections.swap(list, index1, index2);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        ArrayList<Person> list = new ArrayList<>();
        list.add(new Person("Alice", 25));
        list.add(new Person("Bob", 30));
        list.add(new Person("Charlie", 35));
        list.add(new Person("David", 40));

        System.out.println("Before Swap: " + list);
        swapElements(list, 0, 3);
        swapElements(list, 1, 2);
        System.out.println("After Swap: " + list);
    }
}

Save the Java file, then compile and run it.

javac ~/project/SwapFunction.java && java SwapFunction

You should see the following output:

Before Swap: [Alice (25), Bob (30), Charlie (35), David (40)]
After Swap: [David (40), Charlie (35), Bob (30), Alice (25)]

Summary

In this lab, you learned how to create a Java swap() function using the Collections.swap() method. You learned how to create a function that accepts a list of any data type, how to use the Collections.swap() method to swap two elements at specified indexes, and how to handle exceptions. You also learned how to swap elements in an array and in a list of custom objects.

Other Java Tutorials you may like