2 different ways to swap two elements in an ArrayList in Java

How to swap two elements in an ArrayList in Java:

In this post, we will learn how to swap two elements in an ArrayList in Java based on their indices. We will take the index positions from the user and swap the values in that ArrayList. Collections class provides one static method called swap to swap two elements in a collection and we can use it to swap two values in an ArrayList. Or, if you don’t want to use this method, then you can use get and set methods of ArrayList to swap two values.I will show you both of these methods to swap values in an ArrayList :

Method 1: Swap two elements using get and set methods of ArrayList:

In this method, we will use the get and set methods of ArrayList. get method is used to get one value in an ArrayList using an index and set is used to assign one value in an arraylist in an index position.

So, this program will:

  • get the value from the first index and keep it in a variable.
  • Assign the value of second index to first index in the arraylist.
  • Assign the first index value that we stored in first step to second index.

That’s all. It is same as like swapping two numbers using a third variable.

Below is the complete Java program:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        int firstIndex, secondIndex;
        Scanner sc = new Scanner(System.in);

        ArrayList<Integer> intList = new ArrayList<>();

        for(int i = 1; i< 10; i++){
            intList.add(i);
        }

        System.out.println("Enter the first index :");
        firstIndex = sc.nextInt();

        System.out.println("Enter the second index :");
        secondIndex = sc.nextInt();

        System.out.println("Original list before swap : "+intList);

        int element = intList.get(firstIndex);
        intList.set(firstIndex, intList.get(secondIndex));
        intList.set(secondIndex, element);

        System.out.println("List after swap : "+intList);
    }
}

Here,

  • firstIndex and secondIndex are two integer variables to store the index values entered by the user.
  • sc is a Scanner object to read the user input.
  • intList is an integer ArrayList. Using a for loop, we are adding 1 to 9 to this ArrayList.
  • We are taking the values of first and the second index from the user as inputs.
  • Before and after swapping the values of the ArrayList, we are printing it to the user. The swapping is done in three steps as I explained before.

Sample Output:

Below are sample outputs of the above program:

Enter the first index :
2
Enter the second index :
3
Original list before swap : [1, 2, 3, 4, 5, 6, 7, 8, 9]
List after swap : [1, 2, 4, 3, 5, 6, 7, 8, 9]

Enter the first index :
4
Enter the second index :
6
Original list before swap : [1, 2, 3, 4, 5, 6, 7, 8, 9]
List after swap : [1, 2, 3, 4, 7, 6, 5, 8, 9]

Method 2: Swap using Collections.swap :

Collections.swap is a straight forward method to swap two values in an ArrayList. This method is defined as below:

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

Here, we can pass the list that we want to do the swapping and the first and the second index i and j. It will modify the list.

Let me change the above program to use Collections.swap :

import java.util.*;

public class Main {
    public static void main(String[] args) {
        int firstIndex, secondIndex;
        Scanner sc = new Scanner(System.in);

        ArrayList<Integer> intList = new ArrayList<>();

        for(int i = 1; i< 10; i++){
            intList.add(i);
        }

        System.out.println("Enter the first index :");
        firstIndex = sc.nextInt();

        System.out.println("Enter the second index :");
        secondIndex = sc.nextInt();

        System.out.println("Original list before swap : "+intList);

        Collections.swap(intList, firstIndex, secondIndex);

        System.out.println("List after swap : "+intList);
    }
}

We are doing exactly the same as the above program. Only one line is changed instead of three steps.

You will get similar outputs:

Enter the first index :
3
Enter the second index :
8
Original list before swap : [1, 2, 3, 4, 5, 6, 7, 8, 9]
List after swap : [1, 2, 3, 9, 5, 6, 7, 8, 4]

Exception:

Both of these examples will throw IndexOutOfBoundsException for invalid index. So, make sure to check for the index if it is valid or not or use one try-catch handler.

Enter the first index :
100
Enter the second index :
20
Original list before swap : [1, 2, 3, 4, 5, 6, 7, 8, 9]
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 100 out of bounds for length 9
	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
	at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
	at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
	at java.base/java.util.Objects.checkIndex(Objects.java:373)
	at java.base/java.util.ArrayList.get(ArrayList.java:426)
	at java.base/java.util.Collections.swap(Collections.java:501)
	at com.company.Main.main(Main.java:24)

Solution 1: Check for index valid or not :

We can check if the input indices are valid or not as like below :

if(firstIndex < 0 || firstIndex > intList.size() || secondIndex < 0 || secondIndex > intList.size()){
    System.out.println("Please enter valid index !!");
}else {
    System.out.println("Original list before swap : " + intList);

    Collections.swap(intList, firstIndex, secondIndex);

    System.out.println("List after swap : " + intList);
}

It will do the swapping only if firstIndex and secondIndex are valid.

Solution 2: Use a try-catch block:

Or, we can use one try-catch block:

try {
    Collections.swap(intList, firstIndex, secondIndex);
    System.out.println("List after swap : " + intList);
} catch (IndexOutOfBoundsException e) {
    System.out.println("Invalid index found !!");
}

It will try to swap the values and if any exception is thrown, it will move to the catch block. You can use any one of these two methods but make sure to handle exception if you are not sure about the inputs.

You might also like: