Collections 工具类常用方法

面试官问:"Collections 和 Collection 有什么区别?"

候选人小周答:"Collection 是接口,Collections 是工具类。"

面试官追问:"那你用过 Collections 的哪些方法?"

小周说:"呃... Collections.sort() 排序... Collections.reverse() 反转..."

面试官继续问:"二分查找用什么方法?对线程安全集合呢?"

小周彻底答不上来了。

【面试官心理】 这道题考查的是候选人对 Java 标准库的掌握程度。Collections 是开发中离不开的工具类,但很多人只用过排序和反转,其他方法都不熟悉。


一、Collections vs Collection

名称类型说明
Collection接口Java 集合框架的根接口之一
Collections工具类所有方法都是 static,操作 Collection 对象

二、排序与查找 🔴

2.1 排序 sort()

List<Integer> list = new ArrayList<>(Arrays.asList(5, 2, 8, 1, 9));
Collections.sort(list);
// [1, 2, 5, 8, 9]

2.2 二分查找 binarySearch()(必须先排序!)

List<Integer> list = new ArrayList<>(Arrays.asList(1, 3, 5, 7, 9));
Collections.sort(list);

int index = Collections.binarySearch(list, 5);  // 2
int index2 = Collections.binarySearch(list, 4); // 负数(未找到)

2.3 反转 reverse()

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Collections.reverse(list);
// [5, 4, 3, 2, 1]

2.4 洗牌 shuffle()

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Collections.shuffle(list);
// 随机打乱顺序

三、批量操作 🔴

3.1 批量赋值 fill()

List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
Collections.fill(list, "x");
// ["x", "x", "x"]

3.2 批量复制 copy()

List<String> source = Arrays.asList("a", "b", "c");
List<String> dest = new ArrayList<>(Arrays.asList("x", "y", "z"));
Collections.copy(dest, source);
// dest 变成 ["a", "b", "c"]

3.3 批量交换 swap()

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Collections.swap(list, 0, 4);
// [5, 2, 3, 4, 1]

四、极值与统计 🟡

List<Integer> list = new ArrayList<>(Arrays.asList(3, 1, 4, 1, 5, 9));

int max = Collections.max(list);  // 9
int min = Collections.min(list);  // 1

五、线程安全封装 🔴

5.1 同步集合 synchronizedXXX()

List<String> list = new ArrayList<>();
List<String> safeList = Collections.synchronizedList(list);

Map<String, Integer> map = new HashMap<>();
Map<String, Integer> safeMap = Collections.synchronizedMap(map);
⚠️

Collections.synchronizedList() 返回的集合在遍历时必须手动加锁:

synchronized(safeList) {
    for (String s : safeList) {
        System.out.println(s);
    }
}

5.2 不可变集合

List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
List<String> unmodifiable = Collections.unmodifiableList(list);
// 任何修改操作都会抛 UnsupportedOperationException

5.3 单元素集合

Set<String> singleton = Collections.singleton("only");
Map<String, Integer> singletonMap = Collections.singletonMap("key", 1);

六、方法速查表

方法用途
sort()排序
binarySearch()二分查找
reverse()反转顺序
shuffle()随机打乱
fill()批量赋值
copy()批量复制
swap()交换元素
max() / min()极值
synchronizedList()线程安全封装
unmodifiableList()不可变封装
singletonXXX()单元素集合

七、面试官追问 🔴

面试官:"Collections.sort()Arrays.sort() 有什么区别?"

标准回答

  • Collections.sort() 操作 List
  • Arrays.sort() 操作数组
  • 底层最终都调用了 TimSort.sort()Dual-Pivot Quicksort

面试官追问:"Collections.binarySearch() 查找一个没排序的 list 会怎样?"

标准回答:结果是未定义的,可能找到错误的位置或者返回负数。