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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/generics("`Generics`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/inner_classes("`Inner Classes`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/arraylist("`ArrayList`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_attributes("`Class Attributes`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/constructors("`Constructors`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/encapsulation("`Encapsulation`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("`Exceptions`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/SystemandDataProcessingGroup -.-> java/object_methods("`Object Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-117432{{"`Creating a Swap Function`"}} java/generics -.-> lab-117432{{"`Creating a Swap Function`"}} java/inner_classes -.-> lab-117432{{"`Creating a Swap Function`"}} java/arraylist -.-> lab-117432{{"`Creating a Swap Function`"}} java/classes_objects -.-> lab-117432{{"`Creating a Swap Function`"}} java/class_attributes -.-> lab-117432{{"`Creating a Swap Function`"}} java/class_methods -.-> lab-117432{{"`Creating a Swap Function`"}} java/constructors -.-> lab-117432{{"`Creating a Swap Function`"}} java/encapsulation -.-> lab-117432{{"`Creating a Swap Function`"}} java/exceptions -.-> lab-117432{{"`Creating a Swap Function`"}} java/modifiers -.-> lab-117432{{"`Creating a Swap Function`"}} java/oop -.-> lab-117432{{"`Creating a Swap Function`"}} java/identifier -.-> lab-117432{{"`Creating a Swap Function`"}} java/arrays -.-> lab-117432{{"`Creating a Swap Function`"}} java/comments -.-> lab-117432{{"`Creating a Swap Function`"}} java/data_types -.-> lab-117432{{"`Creating a Swap Function`"}} java/operators -.-> lab-117432{{"`Creating a Swap Function`"}} java/output -.-> lab-117432{{"`Creating a Swap Function`"}} java/strings -.-> lab-117432{{"`Creating a Swap Function`"}} java/object_methods -.-> lab-117432{{"`Creating a Swap Function`"}} java/system_methods -.-> lab-117432{{"`Creating a Swap Function`"}} end

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