交换向量元素的Java程序
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 。
示例 1:
Java
// Java program to Swap Elements of Java Vector
import java.util.Collections;
import java.util.Vector;
public class GFG {
public static void main(String[] args)
{
// create vector
Vector vector = new Vector();
// insert elements in vector
vector.add("A");
vector.add("B");
vector.add("C");
vector.add("D");
vector.add("E");
// print original vector
System.out.println("Before Swapping = "+vector);
// call Collection.swap() method
Collections.swap(vector, 0, 4);
// print vector after swap two elements
System.out.println("After Swapping = "+vector);
}
}
Java
// 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
List vector = new ArrayList();
// populate the vector
vector.add("rohan");
vector.add("manish");
vector.add("simran");
vector.add("ananya");
vector.add("ishika");
// 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);
}
}
}
输出
[A, B, C, D, E]
After swapping
[E, B, C, D, A]
示例 2:对于IndexOutOfBoundsException
Java
// 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
List vector = new ArrayList();
// populate the vector
vector.add("rohan");
vector.add("manish");
vector.add("simran");
vector.add("ananya");
vector.add("ishika");
// 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: [rohan, manish, simran, ananya, ishika]
Trying to swap elements more than upper bound index
Exception thrown : java.lang.IndexOutOfBoundsException: Index 5 out of bounds for length 5