In Java, the swap() method is a built-in static function of the Collections class that is imported from the “java.util” package. It swaps the two elements at the specified indexes within the List. The return type of the swap() is void. However, the List given to the swap() method will be modified as the positions of the elements will be interchanged. The swap() method does not modify the List if the indexes specified for swapping are equal.
Quick Outline
This article covers the following aspects:
How to Use the Swap() Method in Java?
In user-defined functions, the swapping is performed by using the third variable for storing values and then swapping them. However, the user-defined approach is limited in terms of calling the function in different classes, performance aspects, or extensive code. On the other hand, the Collections.swap() method is suitable for swapping the two elements of a List, ArrayList, or collections of objects.
Syntax
The swap() method accepts three arguments as shown in the syntax below:
Collections.swap(List, int index1, int index2)
Here:
- Collections is the class that invokes the static swap() function.
- In the swap() method, the “List” argument refers to any List or collection of objects in which the elements are to be swapped.
- The “index1” and “index2” are two integer arguments that are to be swapped with each other.
Now, let’s explore different Examples to understand the working of the Collections.swap() method.
Example 1: Swap Using the Collections.swap() Method
The import statement includes all the essential dependencies and classes from the “java.util” package. Within the main() method, the List class creates an instance “programLanguages” of the String data type. The Arrays.asList() method forms a list of the mentioned elements. The Collections.swap() methods swap the elements at the 2nd and 1st index of the “programLanguages” List. The println() method then displays the List before and after swapping:
package swapMethod;
import java.util.*;
public class swapMethod {
public static void main(String[] args) {
List <String> programLanguages = Arrays.asList("C++", "Java" , "Python");
System.out.println("Before swapping " + programLanguages);
Collections.swap(programLanguages, 2, 1);
System.out.println("After swapping is " + programLanguages) ;
}
}
Output
The output is given as follows:
Example 2: Swapping the Elements for the ArrayList Using Collections.swap()
ArrayList is the collection of elements that grows and shrinks according to the storage requirement. Aside from using the swap() method with the List, we can also use the ArrayList with it.
In this example, the essential dependencies and methods are imported from the java.util package:
import java.util.*;
Inside the main() program, the ArrayList class creates an instance “programLanguages” of the “String” data type. The add() method is called using the “programLanguages”. The ArrayList “programLanguages” before swapping is then printed to provide a comparison:
ArrayList<String> programLanguages = new ArrayList<>(); //created an ArrayList
//add the elements to the ArrayList
programLanguages.add("C++");
programLanguages.add( "Java");
programLanguages.add("Python");
System.out.println("Before swapping " + programLanguages);
The “Collections.swap()” method takes the following arguments and swaps the elements at the given indexes within the “programLanguages” ArrayList. The output is then printed:
//Swap ElementsCollections.swap(programLanguages, 0, 1);
System.out.println("After swapping is " + programLanguages) ;
Output
The output is given in the following snapshot:
Note: Collection.swap() does not work on the Arrays.
Example 3: Swapping the Elements of List of Lists Using the Collections.swap()
A list is a collection/group of objects that can store duplicate values/elements. The List of Lists is a two-dimensional data structure that stores lists at indexes. One List is stored at one index in List of Lists structures. The Collections.swap() method works efficiently for the List of Lists data structure.
In the following code, the import statement is used to include all the required classes and dependencies from the “java.util” package:
import java.util.*;
Inside the main() method, a “List of lists” of integer data types is declared. Similarly, two more lists are declared i.e., firstInnerList and secondInnerList. These two lists are added to the “listOfLists” and are stored at the contiguous memory locations:
List <List <Integer>> listOfLists = new ArrayList<>();
List<Integer> firstInnerList = new ArrayList<>();
List<Integer> secondInnerList = new ArrayList<>();
The “firstInnerList” and “secondInnerList” call the add() method that appends the specified elements to the lists:
//creates First inner List
firstInnerList.add(1);
firstInnerList.add(2);
//creates Second Inner List
secondInnerList.add(3);
secondInnerList.add(4);
The “firstInnerList” and “secondInnerList” are then added to the “listOfLists” using the add() function. The println() method prints the “listOfList” before swapping to provide a comparison between the original and modified List of Lists:
//Adds the two list to the "List of List"
listOfLists.add(firstInnerList);
listOfLists.add(secondInnerList);
System.out.println("Before Swapping : " + listOfLists);
The Collections.swap() method accepts “listOfLists” and the two indexes for swapping. The “firstInnerList” is stored at the 0 index and the “secondInnerList” is stored at the “1st” index. However, when the output is printed, the two lists are swapped using the swap() method:
//Swaps the Elements
Collections.swap(listOfLists, 1, 0);
//Display Output After Swapping
System.out.println("After Swapping : " + listOfLists);
Output
In the following output, the contents of the two lists are swapped i.e., the positions of the lists are changed:
That is all from the examples to understand the working of the swap() method in Java.
What will Happen for the Non-Existent Index Swapping?
The “IndexOutOfBoundsException” is thrown by the swap() method when the indexes provided for swapping are either negative or do not exist within the List. In the following code, the index provided is negative, however, we know that the index of the List, ArrayList, arrays, etc starts from the 0 index. Therefore, accessing a negative index or an index that doesn’t exist will result in an exception, as shown in the output of the code:
Alternatives For the Collections.swap() Method
Aside from the Collections.swap() method, there are different approaches for swapping elements in Java. You can use any of the below-listed alternatives to achieve the same functionality as the Collections.swap() method.
Method 1: Swapping Using the XOR Operator
In Java, the XOR operator is represented/denoted by the “^” sign. The XOR operator compares the bits and gives 1 when both are opposite/contrasting and vice versa. The Exclusive OR operator can also be used to swap the elements in Java as shown in the code below.
To implement swapping functionality using the XOR operator, first import the essential dependencies and methods from java.util package. Inside the main() method, two integer-type variables are declared and initialized with the respective values. The print() method then displays the values of the integer variables. In the below lines of code, the (b=a) assigns the value of “a” to “b”. The XOR is then taken between the value of “b” and (b=a). It returns 0 as the value of b equals b. Again, the XOR is applied on the “a” and “b” and the result is false. As a result, the values are swapped which is also shown in the print statement:
package swapMethod;
import java.util.*;
public class swapMethod {
public static void main(String[] args) {
int a = 10 ;
int b = 11;
System.out.println("Before Swapping = " + a + " " + b);
//xor operator
a = a ^ b ^ (b = a);
System.out.println(" After Swapping = " + a + " " + b);
}
}
Output
Output is given as follows:
Method 2: Swapping Using the User-Defined Method
In this user-defined approach, a custom function is defined that swaps the two elements at the given index of the array. The code is as follows.
The “swap()” method is the user-defined method that accepts three arguments i.e., the array in which the elements are to be swapped, the two indexes of integer data type that are to be swapped with each other. In this method, another integer-type “temp” variable is declared that stores the value of the given index. The “index1” in the “arr” then stores the value at the “arr[index2]”. The temp value is assigned to the “arr[index2]” and hence, the elements are swapped:
public static void swap(int [ ] arr, int index1, int index2)
{
//swapping the elements
int temp=arr[index1];
arr[index1]=arr[index2];
arr[index2]=temp;
The for loop is used to print the swapped elements of the array “arr”. The loop starts from i=0 and terminates when the value of “i” exceeds(becomes greater than) the “arr.length”. The value of “i” is increased in every iteration. The print() method prints the value at the “i” index of the “arr”:
//elements are displayed using the for loop
for (int i=0;i<arr.length;i++)
{
System.out.print(arr[i] + " ");
}
}
Inside the main() method, an integer array is created with the following values. The for loop iterates over the elements of the array before swapping:
public static void main(String[] args) {
int[ ] numArray= {1,2,3,4,5}; //integer array declared
System.out.println("Before Swapping ");
for(int i=0;i<numArray.length;i++) //prints numArray elements before swapping
{
System.out.print(numArray[i] + " ");
}
The print statements provide a comparison between the original array before swapping and after swapping. The swap() function is called which was explained earlier. The three arguments are provided i.e., numArray and the values are swapped at the given indexes:
System.out.println( "\n" + "----Output After Swapping------ ");
swap(numArray, 1,2); //calls the function
}
Complete Code & Output
That is all from this article.
Conclusion
The Collections.swap() method interchanges the two values at the given index within the List or collection of the object as shown in this article. The swap() method accepts a List and the two indexes that are to be swapped. In Java, other than the Collections.swap() method, developers can also use the user-defined method or XOR operator.