📜  array.swap java (1)

📅  最后修改于: 2023-12-03 15:29:28.383000             🧑  作者: Mango

Array.swap() in Java

The swap() method in Java is a method available in the java.util package that can be used to interchange the values of two elements in an array. The swap() method can be used on all types of arrays including primitive data type arrays.

Syntax

The syntax of the swap() method in Java is as follows:

public static void swap(Object[] array, int index1, int index2)

Here,

  • array - This is the array in which elements would be swapped
  • index1 - The index of the first element to be swapped
  • index2 - The index of the second element to be swapped
Example
import java.util.Arrays;

public class ArraySwapExample {
    public static void main(String[] args) {
        String[] array = {"apple", "banana", "cherry", "grape", "kiwi"};
        System.out.println("Array before swap: " + Arrays.toString(array));
        Arrays.swap(array, 1, 3);
        System.out.println("Array after swap: " + Arrays.toString(array));
    }
}

Output:

Array before swap: [apple, banana, cherry, grape, kiwi]
Array after swap: [apple, grape, cherry, banana, kiwi]
Points to remember
  • The swap() method in Java is available in the java.util package
  • The swap() method can be used to interchange the values of two elements in an array
  • The swap() method can be used on all types of arrays including primitive data type arrays
  • The swap() method takes three parameters - The array in which elements would be swapped, the index of first element, and the index of the second element