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 program to demonstrate
// swap() method for String value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// creating object of List<String>
List<String> vector = new ArrayList<String>();
// populate the vector
vector.add("A");
vector.add("B");
vector.add("C");
vector.add("D");
vector.add("E");
// pritning the vector before swap
System.out.println("Before swap: " + vector);
// swap the elements
System.out.println("\nSwapping 0th and 4th element.");
Collections.swap(vector, 0, 4);
// priting the vector after swap
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 program to demonstrate
// swap() method for IndexOutOfBoundsException
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
// creating object of List<String>
List<String> vector = new ArrayList<String>();
// populate the vector
vector.add("A");
vector.add("B");
vector.add("C");
vector.add("D");
vector.add("E");
// pritning the vector before swap
System.out.println("Before swap: " + vector);
// swap the elements
System.out.println("\nTrying to swap elements"
+ " more than upper bound index ");
Collections.swap(vector, 0, 5);
// priting the vector after swap
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
相关用法
- Java Collections min()用法及代码示例
- Java Collections max()用法及代码示例
- Java Collections checkedSortedMap()用法及代码示例
- Java Collections checkedList()用法及代码示例
- Java Collections checkedSortedSet()用法及代码示例
- Java Collections indexOfSubList()用法及代码示例
- Java Collections fill()用法及代码示例
- Java Collections copy()用法及代码示例
- Java Collections enumeration()用法及代码示例
- Java Collections checkedCollection()用法及代码示例
- Java Collections addAll()用法及代码示例
- Java Collections asLifoQueue()用法及代码示例
- Java Collections unmodifiableMap()用法及代码示例
- Java Collections unmodifiableSet()用法及代码示例
注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 Collections swap() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。