📜  在Java中交换列表的项目:Collections.swap() 与示例

📅  最后修改于: 2022-05-13 01:54:59.161000             🧑  作者: Mango

在Java中交换列表的项目:Collections.swap() 与示例

Java.util.Collections.swap()方法是一个Java.util.Collections 类方法。它交换给定列表中指定位置的元素。

// Swaps elements at positions "i" and "j" in myList.
public static void swap(List mylist, int i, int j)

It throws IndexOutOfBoundsException if either i
or j is out of range.
// Java program to demonstrate working of Collections.swap
import java.util.*;
  
public class GFG
{
    public static void main(String[] args)
    {
        // Let us create a list with 4 items
        ArrayList  mylist =
                        new ArrayList();
        mylist.add("code");
        mylist.add("practice");
        mylist.add("quiz");
        mylist.add("geeksforgeeks");
  
        System.out.println("Original List : \n" + mylist);
  
        // Swap items at indexes 1 and 2
        Collections.swap(mylist, 1, 2);
  
        System.out.println("\nAfter swap(mylist, 1, 2) : \n"
                           + mylist);
  
        // Swap items at indexes 1 and 3
        Collections.swap(mylist, 3, 1);
  
        System.out.println("\nAfter swap(mylist, 3, 1) : \n"
                           + mylist);
    }
}

输出:

Original List : Original List : 
[code, practice, quiz, geeksforgeeks]

After swap(mylist, 1, 2) : 
[code, quiz, practice, geeksforgeeks]

After swap(mylist, 3, 1) : 
[code, geeksforgeeks, practice, quiz]