如何在Java中交换 ArrayList 中的两个元素?
我们可以使用 Collections.swap() 方法交换 Array List 的两个元素。此方法接受三个参数。第一个参数是 ArrayList,另外两个参数是元素的索引。此方法不返回任何内容。
句法:
public static void swap(List list, int a, int b);
参数
- list : 一个ArrayList或任何 List 实现类,在其中交换元素
- a:第一个元素的索引
- b : 第二个元素的索引
例外:如果 Array List 的索引小于 0 或大于 ArrayList 的大小,则抛出IndexOutOfBoundsException 。
示例 1
Java
// Java program to swap two elements in an ArrayList
import java.util.ArrayList;
import java.util.Collections;
public class GFG {
public static void main(String a[])
{
// Create the Array List
ArrayList ArrList = new ArrayList();
// add the values in Array List
ArrList.add("Item 1");
ArrList.add("Item 2");
ArrList.add("Item 3");
ArrList.add("Item 4");
ArrList.add("Item 5");
// display Array List before swap
System.out.println("Before Swap the ArrayList ");
System.out.println(ArrList);
// Swapping the elements at 1 and 2 indices
Collections.swap(ArrList, 1, 2);
// display Array List after swap
System.out.println("After Swap the ArrayList");
System.out.println(ArrList);
}
}
Java
// Java program to swap two elements in an ArrayList
import java.util.ArrayList;
import java.util.Collections;
public class GFG {
public static void main(String a[]) throws Exception
{
// Create the Array List
ArrayList ArrList = new ArrayList();
// add the values in Array List
ArrList.add("Item 1");
ArrList.add("Item 2");
ArrList.add("Item 3");
ArrList.add("Item 4");
ArrList.add("Item 5");
// display Array List before swap
System.out.println("Before Swap the ArrayList ");
System.out.println(ArrList);
// Swapping the elements at -1 and 2 indices
// Throws IndexOutOfBounds Exception
Collections.swap(ArrList, -1, 2);
}
}
输出
Before Swap the ArrayList
[Item 1, Item 2, Item 3, Item 4, Item 5]
After Swap the ArrayList
[Item 1, Item 3, Item 2, Item 4, Item 5]
示例 2
Java
// Java program to swap two elements in an ArrayList
import java.util.ArrayList;
import java.util.Collections;
public class GFG {
public static void main(String a[]) throws Exception
{
// Create the Array List
ArrayList ArrList = new ArrayList();
// add the values in Array List
ArrList.add("Item 1");
ArrList.add("Item 2");
ArrList.add("Item 3");
ArrList.add("Item 4");
ArrList.add("Item 5");
// display Array List before swap
System.out.println("Before Swap the ArrayList ");
System.out.println(ArrList);
// Swapping the elements at -1 and 2 indices
// Throws IndexOutOfBounds Exception
Collections.swap(ArrList, -1, 2);
}
}
输出
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index -1 out of bounds for length 5
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:372)
at java.base/java.util.ArrayList.get(ArrayList.java:458)
at java.base/java.util.Collections.swap(Collections.java:501)
at GFG.main(GFG.java:27)