CodeGym/Java Blog/Java Objects/How to swap objects in Java?
Author
Vasyl Malik
Senior Java Developer at CodeGym

How to swap objects in Java?

Published in the Java Objects group
members
Swapping objects is one of the most popular actions in programming. It’s particularly useful in sorting. What happens in swapping is two variables exchanging their values. In this article, we learn how to swap objects in Java in two different cases. One is swapping independent objects and the other is swapping two objects in a List or an Array. Let’s first examine swapping independent objects.How to swap objects in Java? - 1

Swapping objects is different from swapping primitive data types

One of the common methods to use to swap primitive values is using a temporal variable. However, you know Java uses “Pass by Value” when passing parameters to a method. Therefore, swapping objects won’t work as you expected with this method. The following example will show it.
public class ObjectSwapper {
    public static void main(String[] args) {
        InnerClass obj1 = new InnerClass(12345);
        InnerClass obj2 = new InnerClass(11111);
        swap(obj1, obj2);
        System.out.println("Obj1 ID value : " + obj1.id + "\n" + "Obj2 ID value :  " + obj2.id);
    }
    static void swap(InnerClass x, InnerClass y) {
        InnerClass temp;
        temp = x;
        x = y;
        y = temp;
    }
    static class InnerClass {
        public int id;
        public InnerClass(int Id) {
            this.id = Id;
        }
    }
}
The output:How to swap objects in Java? - 2There was no swapping! When we call the swap method and pass the objects, we pass a copy of the object, with all the property values. This is the reason why it is called “Pass by Value”. The swap method actually swaps the objects impacting only the copy of the original object. So the original objects are kept unchanged. The solution to this would be to use a wrapper class to wrap the two objects.

Swapping objects with a wrapper class

public class ObjectSwapper {
    public static void main(String[] args) {

        InnerClass obj1 = new InnerClass(12345);
        InnerClass obj2 = new InnerClass(11111);
        objectWrapper wrapperObj1 = new objectWrapper(obj1);
        objectWrapper wrapperObj2 = new objectWrapper(obj2);
        // Values before swapping
        System.out.println("WrapperObj1 InncerClass ID value : " + wrapperObj1.innerObject.id + "\n" + "WrapperObj2 InncerClass ID value : "
                + wrapperObj2.innerObject.id + "\n");

        swap(wrapperObj1, wrapperObj2);

        // Values after swapping
        System.out.println("WrapperObj1 InncerClass ID value : " + wrapperObj1.innerObject.id + "\n" + "WrapperObj2 InncerClass ID value : "
                + wrapperObj2.innerObject.id);
    }

       static void swap(objectWrapper wrapperObj1, objectWrapper wrapperObj2) {
        InnerClass temp;
        temp = wrapperObj1.innerObject;
        wrapperObj1.innerObject = wrapperObj2.innerObject;
        wrapperObj2.innerObject = temp;
    }

    static class InnerClass {
        public int id;
        public InnerClass(int Id) {
            id = Id;
        }
    }

    static class objectWrapper {
        InnerClass innerObject;
        public objectWrapper(InnerClass objInnner) {
            this.innerObject = objInnner;
        }
    }
}
Here we used a wrapper class that has a property of the type of objects we need to swap. By using a simple swap method, it swaps the content of the InnerClass objects of the wrapper class objects. For any further implementation of the swapped InnerClass objects, we can use wrapperObj1.xyz and wrapperObj2.xyz accordingly. The output:How to swap objects in Java? - 3

The built-in swap() method in Java

The Java Collections Framework’s classes have a built-in method to swap elements called swap(). The java.util is a utility class that contains static methods that can operate on elements like Lists from the Collection interface. Using the swap method is much easier than the example we discussed earlier. The swap() method is a static method and therefore you invoke it with the class name as Collections.swap(). The return type of the swap() method is void so it will not return anything. You need to pass three arguments to the swap() method. Check the note below.
swap(List<?> list, int a, int b)
Parameters:
  • list — list contains the elements we swap.
  • a — index of an element to be swapped.
  • b — index of another element to be swapped.
Note that this method will throw an IndexOutOfBoundsException if either a or b is out of the range of the list size. The maximum index of the list is one less than the size of the list. Any index value more than that will cause the IndexOutOfBoundsException to be thrown. An example of how to use the swap method on an ArrayList is shown below.

swap() method on an ArrayList

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ArrayListSwapper {
    public static void main(String[] args) {
        try {
            List fruits = new ArrayList();
            fruits.add("Mango");
            fruits.add("Papaya");
            fruits.add("Apple");
            fruits.add("Orange");
            fruits.add("Watermelon");
            fruits.add("Bael");
            System.out.println("Before swapping : " + fruits);
         //using Collection.swap() method
            Collections.swap(fruits, 2, 5);
            System.out.println("After swapping : " + fruits);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Index Out of Bound Exception thrown : " + e);
        }
    }
}
The ArrayList of fruits contains six elements. We swap the 2nd and 5th elements using the function swap() method. The best practice is to write the swap() method within a try-catch block as it can throw an IndexOutOfBoundsException at run time. The output:How to swap objects in Java? - 4If we pass ‘2’ and ‘8’ as indexes the application will throw an exception as the size of the list is six.
Collections.swap(fruits, 2, 8);
The output will be:How to swap objects in Java? - 5

Conclusion

In this tutorial, we discussed a couple of swapping techniques used in Java. One of them is using a wrapper class and the other is using Collection.swap() method. It is important to remember that exception handling should be done when using the function swap() as it throws a runtime exception.
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet