📅  最后修改于: 2023-12-03 15:29:28.383000             🧑  作者: Mango
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.
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 swappedindex1
- The index of the first element to be swappedindex2
- The index of the second element to be swappedimport 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]
swap()
method in Java is available in the java.util
packageswap()
method can be used to interchange the values of two elements in an arrayswap()
method can be used on all types of arrays including primitive data type arraysswap()
method takes three parameters - The array in which elements would be swapped, the index of first element, and the index of the second element