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


Java java.util.Collections.swap(List<?>, int, int)用法及代碼示例


描述

這個swap(List<?>, int, int)方法用於交換指定列表中指定位置的元素。

聲明

以下是聲明java.util.Collections.swap()方法。

public static void swap(List<?> list,int i,int j)

參數

  • list- 交換元素的列表。

  • i− 要交換的一個元素的索引。

  • j- 要交換的其他元素的索引。

返回值

NA

異常

IndexOutOfBoundsException- 如果 i 或 j 超出範圍(i < 0 || i >= list.size() || j < 0 || j >= list.size()),則拋出此錯誤。

示例

下麵的例子展示了 java.util.Collections.swap() 的用法

package com.tutorialspoint;

import java.util.*;

public class CollectionsDemo {
   public static void main(String[] args) {
      
      // create vector object 
      Vector<String> vector = new Vector<String>();

      // populate the vector
      vector.add("1");
      vector.add("2");
      vector.add("3");
      vector.add("4");
      vector.add("5");

      System.out.println("Before swap:"+vector);

      // swap the elements
      Collections.swap(vector, 0, 4);

      System.out.println("After swap:"+vector);
   }
}

讓我們編譯並運行上麵的程序,這將產生以下結果。

Before swap:[1, 2, 3, 4, 5]
After swap:[5, 2, 3, 4, 1]

相關用法


注:本文由純淨天空篩選整理自 java.util.Collections.swap(List<?>, int, int) Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。