當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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 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


相關用法


注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 Collections swap() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。