Java中的Collections swap()方法及示例
java.util.Collections 类中的 swap() 方法用于交换指定列表中指定位置的元素。如果指定位置相等,则调用此方法不会更改列表。
语法:
public static void swap(List list, int i, int j)
参数: 该方法接受以下参数
- list – 要交换元素的列表。
- i – 要交换的一个元素的索引。
- j – 要交换的另一个元素的索引。
异常 如果i或j超出范围(i = list.size() || j = list.size()),则此方法会抛出 IndexOutOfBoundsException
下面是说明 swap() 方法的示例
示例 1:
// Java程序演示
// 用于String值的swap()方法
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
//创建一个List对象
List vector = new ArrayList();
//填充向量
vector.add("A");
vector.add("B");
vector.add("C");
vector.add("D");
vector.add("E");
//打印交换前的向量
System.out.println("Before swap: " + vector);
//交换元素
System.out.println("\nSwapping 0th and 4th element.");
Collections.swap(vector, 0, 4);
//打印交换后的向量
System.out.println("\nAfter swap: " + vector);
}
catch (IndexOutOfBoundsException e) {
System.out.println("\nException thrown : " + e);
}
}
}
输出:
Before swap: [A, B, C, D, E]
Swapping 0th and 4th element.
After swap: [E, B, C, D, A]
示例 2:
对于 IndexOutOfBoundsException
// Java程序演示
// 用于IndexOutOfBoundsException的swap()方法
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
//创建一个List对象
List vector = new ArrayList();
//填充向量
vector.add("A");
vector.add("B");
vector.add("C");
vector.add("D");
vector.add("E");
//打印交换前的向量
System.out.println("Before swap: " + vector);
//交换元素
System.out.println("\nTrying to swap elements"
+ " more than upper bound index ");
Collections.swap(vector, 0, 5);
//打印交换后的向量
System.out.println("After swap: " + vector);
}
catch (IndexOutOfBoundsException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出:
Before swap: [A, B, C, D, E]
Trying to swap elements more than upper bound index
Exception thrown : java.lang.IndexOutOfBoundsException: Index: 5, Size: 5