类签名与继承体系
Declaration
public class Collections extends Object
继承 / 实现关系:
java.lang.Object -> java.util.Collections (工具类,私有构造)
设计原理与核心定位
Collections 聚合了针对 Collection、List、Set 和 Map 的经典通用算法。对于接口返回值,推荐使用 Collections.emptyList() 或 JDK 9+ 的 List.of() 代替返回 null,消除调用方空指针隐患。
核心属性与常量
| 属性 / 常量 | 修饰符与类型 | 说明与作用 |
|---|---|---|
EMPTY_LIST / EMPTY_SET / EMPTY_MAP |
public static final |
零内存分配的不可变空集合常量(建议使用泛型方法 emptyList())。 |
常用方法详解
| 方法签名 | 返回值 | 复杂度 / 并发特性 | 功能说明 |
|---|---|---|---|
unmodifiableList(List<? extends T>) |
List<T> |
只读视图 | 返回只读包装视图(注意:底层原集合被修改仍会反映出来)。 |
binarySearch(List, T key) |
int |
O(log n) | 在已排序列表中进行二分查找,未找到返回 -(插入点) - 1。 |
disjoint(Collection, Collection) |
boolean |
集合交集判空 | 判断两个集合是否完全没有公共元素。 |
frequency(Collection, Object o) |
int |
O(n) | 统计指定元素在集合中出现的次数。 |
newSetFromMap(Map<E, Boolean>) |
Set<E> |
组合 Set | 基于任意 Map(如 ConcurrentHashMap)快速派生对应特性的 Set。 |
完整示例代码
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class CollectionsToolDemo {
public static void main(String[] args) {
List<Integer> sorted = List.of(10, 20, 35, 50, 80);
int idx = Collections.binarySearch(sorted, 35);
System.out.println("Index of 35: " + idx);
// 基于 ConcurrentHashMap 构造线程安全 Set(JDK 8+ 也可直接用 ConcurrentHashMap.newKeySet())
Set<String> concurrentSet = Collections.newSetFromMap(new ConcurrentHashMap<>());
concurrentSet.add("node-1");
System.out.println("Concurrent Set: " + concurrentSet);
}
} 生产避坑与现代 JDK 最佳实践
- 真正不可变副本用 List.copyOf():
Collections.unmodifiableList(src)只是只读视图,若外部继续修改src,视图内容也会随之改变;JDK 10+ 应优先使用List.copyOf(src)。 - synchronizedMap 并发瓶颈:粗粒度全局锁并发度低,多线程环境优先选用
ConcurrentHashMap。