引言:Collections工具类
Collections是Java提供的操作集合的工具类,提供了大量静态方法用于操作集合,如排序、查找、填充、反转等。
注意:
- Collections(注意有s):操作集合(Collection接口的实现类如List、Set)
- Arrays:操作数组
排序操作
sort() - 排序
import java.util.*;
List list = new ArrayList<>();
list.add(5);
list.add(2);
list.add(8);
list.add(1);
System.out.println("排序前: " + list);
Collections.sort(list);
System.out.println("排序后: " + list);
reverseOrder() - 反向排序
List list = Arrays.asList(5, 2, 8, 1);
// 反向排序
Collections.sort(list, Collections.reverseOrder());
System.out.println("反向排序: " + list);
shuffle() - 随机打乱
List list = Arrays.asList(1, 2, 3, 4, 5);
System.out.println("打乱前: " + list);
Collections.shuffle(list);
System.out.println("打乱后: " + list);
查找操作
binarySearch() - 二分查找
重要:二分查找前必须先排序!
List list = Arrays.asList("Apple", "Banana", "Orange");
Collections.sort(list);
int index = Collections.binarySearch(list, "Banana");
System.out.println("Banana的索引: " + index);
max() / min() - 最大值最小值
List list = Arrays.asList(5, 2, 8, 1, 9);
int max = Collections.max(list);
int min = Collections.min(list);
System.out.println("最大值: " + max);
System.out.println("最小值: " + min);
批量操作
fill() - 填充
List list = new ArrayList<>(Arrays.asList("a", "b", "c", "d"));
System.out.println("填充前: " + list);
Collections.fill(list, "X");
System.out.println("填充后: " + list); // [X, X, X, X]
addAll() - 批量添加
List list = new ArrayList<>();
Collections.addAll(list, "A", "B", "C", "D");
System.out.println("批量添加后: " + list);
copy() - 复制
List source = Arrays.asList("A", "B", "C");
List dest = new ArrayList<>(Arrays.asList("X", "Y", "Z", "W"));
Collections.copy(dest, source);
System.out.println("复制后: " + dest);
集合替换和反转
replaceAll() - 替换所有
List list = new ArrayList<>(Arrays.asList("A", "B", "A", "C", "A"));
Collections.replaceAll(list, "A", "X");
System.out.println("替换后: " + list);
reverse() - 反转
List list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Collections.reverse(list);
System.out.println("反转后: " + list);
rotate() - 旋转
List list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Collections.rotate(list, 2);
System.out.println("旋转2位后: " + list);
集合同步控制
Collections提供了将普通集合转换为线程安全集合的方法:
List list = new ArrayList<>();
List synchronizedList = Collections.synchronizedList(list);
Map map = new HashMap<>();
Map synchronizedMap = Collections.synchronizedMap(map);
Set set = new HashSet<>();
Set synchronizedSet = Collections.synchronizedSet(set);
注意:Java 5+的并发集合(如ConcurrentHashMap)性能更好,如无特殊需要,应优先使用并发集合。
不可变集合
Collections提供了创建不可变(只读)集合的方法:
// 创建不可变列表
List unmodifiableList = Collections.unmodifiableList(
Arrays.asList("A", "B", "C")
);
// 尝试修改会抛出UnsupportedOperationException
// unmodifiableList.add("D"); // 运行时异常!
小结
- Collections是操作集合的工具类,提供静态方法
- 排序:sort()、reverseOrder()、shuffle()
- 查找:binarySearch()(需先排序)、max()、min()
- 批量操作:fill()、addAll()、copy()
- 替换反转:replaceAll()、reverse()、rotate()
- 线程安全:synchronizedList()等方法
- 不可变集合:unmodifiableList()等方法
☕ Java 在线代码编辑器
📝 运行结果