How to Swap Two Elements in an ArrayList in Java?
We can swap two elements of Array List using Collections.swap() method. This method accepts three arguments. The first argument is the ArrayList and the other two arguments are the indices of the elements. This method returns nothing.
Syntax:
public static void swap(List list, int a, int b);
Parameters
- list: An ArrayList or any List implementing class in which elements are swapped
- a: index of the first element
- b: index of the second element
Exception: It throws IndexOutOfBoundsException if the index of Array List is less than 0 or greater than the size of the ArrayList.
Example 1
Java
import java.util.ArrayList;
import java.util.Collections;
public class GFG {
public static void main(String a[])
{
ArrayList<String> ArrList = new ArrayList<String>();
ArrList.add( "Item 1" );
ArrList.add( "Item 2" );
ArrList.add( "Item 3" );
ArrList.add( "Item 4" );
ArrList.add( "Item 5" );
System.out.println( "Before Swap the ArrayList " );
System.out.println(ArrList);
Collections.swap(ArrList, 1 , 2 );
System.out.println( "After Swap the ArrayList" );
System.out.println(ArrList);
}
}
|
Output
Before Swap the ArrayList
[Item 1, Item 2, Item 3, Item 4, Item 5]
After Swap the ArrayList
[Item 1, Item 3, Item 2, Item 4, Item 5]
Example 2
Java
import java.util.ArrayList;
import java.util.Collections;
public class GFG {
public static void main(String a[]) throws Exception
{
ArrayList<String> ArrList = new ArrayList<String>();
ArrList.add( "Item 1" );
ArrList.add( "Item 2" );
ArrList.add( "Item 3" );
ArrList.add( "Item 4" );
ArrList.add( "Item 5" );
System.out.println( "Before Swap the ArrayList " );
System.out.println(ArrList);
Collections.swap(ArrList, - 1 , 2 );
}
}
|
Output
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index -1 out of bounds for length 5
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:372)
at java.base/java.util.ArrayList.get(ArrayList.java:458)
at java.base/java.util.Collections.swap(Collections.java:501)
at GFG.main(GFG.java:27)
Last Updated :
01 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...