JDK 中提供了一个工具类专门用来操作集合,即 Collections,它位于 java.util 包中。Collections 类中提供了大量的方法用于对集合中的元素进行排序、查找和修改等操作。
排序操作
方法声明 | 功能描述 |
---|---|
static boolean addAll(Collection c, T… elements) | 将所有指定元素添加到指定的 collection 中 |
static void reverse(List list) | 反转指定 List 集合中元素的顺序 |
static void shuffle(List list) | 对 List 集合中的元素进行随机排序(模拟玩扑克中的”洗牌”) |
static void sort(List list) | 根据元素的自然顺序对 List 集合中的元素进行排序 |
static void swap(List list, int i, int j) | 将指定 List 集合中 i 处元素和 j 处元素进行交换 |
示例代码:
import java.util.*;
public class Example {
public static void main(String[] args){
ArrayList list = new ArrayList();
Collections.addAll(list, "C", "Z", "B", "K");
System.out.println("排序前:" + list);
Collections.reverse(list);
System.out.println("反转后:" + list);
Collections.sort(list);
System.out.println("按自然顺序排序后:" + list);
Collections.shuffle(list);
System.out.println("洗牌后:" + list);
}
}
查找、替换操作
方法声明 | 功能描述 |
---|---|
static int binarySearch(List list, Object key) | 使用二分法搜索指定对象在 List 集合中的索引,查找的 List 集合中的元素必须是有序的 |
static Object max(Collection col) | 根据元素的自然顺序,返回给定集合中最大的元素 |
static Object min(Collection col) | 根据元素的自然顺序,返回给定集合中最小的元素 |
static boolean replaceAll(List list, Object oldVal, Object newVal) | 用一个新的 newVal 替换 List 集合中所有的旧值 oldVal |
Example.java 示例代码:
import java.util.*;
public class Example {
public static void main(String[] args){
ArrayList list = new ArrayList();
Collections.addAll(list, -3, 2, 9, 5, 8);
System.out.println("集合中的元素:" + list);
System.out.println("集合中的最大元素:" + Collections.max(list));
System.out.println("集合中的最小元素:" + Collections.min(list));
Collections.replaceAll(list, 8, 0); //将集合中的 8 用 0 替换掉
System.out.println("替换后的集合:" + list);
}
}