Collections.swap(List, int, int) in Java

Collections.swap(List, int, int): This method is available in java.util.Collections class of Java.

Syntax:

void java.util.Collections.swap(List<?> list, int i, int j)

This method takes three arguments. This method swaps the elements at the specified positions in the specified list.

Parameters: Three parameters are required for this method.

list: The list in which to swap elements.

i: the index of one element to be swapped.

j: the index of the other element to be swapped.

Throws:

1. IndexOutOfBoundsException - if either i or j is out of range (i < 0 || i >= list.size()|| j < 0 || j >= list.size()).

Approach 1: When no exception

Java

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

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

        List<Integer> arrlist = new ArrayList<Integer>();

        arrlist.add(12);
        arrlist.add(56);
        arrlist.add(899);
        arrlist.add(65);
        arrlist.add(5);

        int i = 1, j = 4;
        Collections.swap(arrlist, i, j);

        System.out.println(arrlist);

    }
}

Output:

[12, 5, 899, 65, 56]


Approach 2: IndexOutOfBoundsException 

Java

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

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

        List<Integer> arrlist = new ArrayList<Integer>();

        arrlist.add(12);
        arrlist.add(56);
        arrlist.add(899);
        arrlist.add(65);
        arrlist.add(5);

        int i = 1, j = 14;
        Collections.swap(arrlist, i, j);

        System.out.println(arrlist);

    }
}

Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 14 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:359) at java.base/java.util.ArrayList.set(ArrayList.java:441) at java.base/java.util.Collections.swap(Collections.java:501)


No comments:

Post a Comment