Home » Java programming language

Java Collections swap() Method with Example

Collections Class swap() method: Here, we are going to learn about the swap() method of Collections Class with its syntax and example.
Submitted by Preeti Jain, on February 07, 2020

Collections Class swap() method

  • swap() method is available in java.util package.
  • swap() method is used to swap the element at index f1 with the element at index f2 in the given list (l).
  • swap() method is a static method, it is accessible with the class name and if we try to access the method with the class object then also we will not get any error.
  • swap() method may throw an exception at the time of assigning index.
    IndexOutOfBoundsException: This exception may throw when the given index f1 or f2 is not in a range.

Syntax:

    public static void swap(List l , int f1, int f2);

Parameter(s):

  • List l – represents the list to swap the elements.
  • int f1 – represents the index of f1 element to swap with other element f2.
  • int f2 – represents the index of f2 element to swap with other element f1.

Return value:

The return type of this method is void, it does not return anything.

Example:

// Java program to demonstrate the example 
// of void swap() method of Collections

import java.util.*;

public class SwapOfCollections {
    public static void main(String args[]) {
        // Instatiates a array list object
        List < Integer > arr_l = new ArrayList < Integer > ();

        // By using add() method is to add
        // objects in an array list 
        arr_l.add(10);
        arr_l.add(20);
        arr_l.add(30);
        arr_l.add(40);
        arr_l.add(50);

        // Display ArrayList
        System.out.println("Array List: " + arr_l);

        // By using swap() method is to swap
        // the element at index 2 with the 
        // element at index 4 in an array list
        Collections.swap(arr_l, 2, 4);

        // Display swapped ArrayList
        System.out.println("Collections.swap(arr_l): " + arr_l);
    }
}

Output

Array List: [10, 20, 30, 40, 50]
Collections.swap(arr_l): [10, 20, 50, 40, 30]



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.