Java Collections swap()方法及实例

Java Collections swap()方法及实例

java.util.Collections 类的 swap() 方法是用来交换指定列表中指定位置的元素的。如果指定的位置相等,调用这个方法可以使列表保持不变。

语法

public static void swap(List list, int i, int j)
Java

参数: 该方法接受以下参数作为参数

  • 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");
 
            // printing 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);
 
            // printing the vector after swap
            System.out.println("\nAfter swap: " + vector);
        }
 
        catch (IndexOutOfBoundsException e) {
            System.out.println("\nException thrown : " + e);
        }
    }
}
Java

输出

Before swap: [A, B, C, D, E]

Swapping 0th and 4th element.

After swap: [E, B, C, D, A]
Java

例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");
 
            // printing 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);
 
            // printing the vector after swap
            System.out.println("After swap: " + vector);
        }
 
        catch (IndexOutOfBoundsException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
Java

输出

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册