Collections是Java中提供集合操作的工具类,包含排序、查找、同步等静态方法;它与Collection接口不同,后者是集合的根接口,前者是操作集合的工具。

在Java的世界里,处理集合数据是家常便饭,而
java.util.Collections
Collection
Collections
Collection
List<String>
List<Integer>
Collections.sort(list)
Comparable
Comparator
Collections.sort(list, comparator)
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
// 排序
List<String> names = new ArrayList<>(Arrays.asList("Alice", "Bob", "Charlie", "David"));
Collections.sort(names);
System.out.println("排序后: " + names); // [Alice, Bob, Charlie, David]
// 逆序
Collections.reverse(names);
System.out.println("逆序后: " + names); // [David, Charlie, Bob, Alice]
// 查找
int index = Collections.binarySearch(names, "Bob", Collections.reverseOrder());
System.out.println("Bob的索引 (逆序查找): " + index); // 2 (因为names是逆序的)
// 填充
List<String> filledList = new ArrayList<>(Collections.nCopies(5, "Hello"));
System.out.println("填充列表: " + filledList); // [Hello, Hello, Hello, Hello, Hello]
// 找到最大/最小元素
List<Integer> numbers = Arrays.asList(10, 5, 20, 15);
System.out.println("最大值: " + Collections.max(numbers)); // 20
System.out.println("最小值: " + Collections.min(numbers)); // 5
// 交换元素
Collections.swap(numbers, 0, 3); // 交换10和15
System.out.println("交换后: " + numbers); // [15, 5, 20, 10]
// 线程安全包装器 (后面会详细聊)
List<String> syncList = Collections.synchronizedList(new ArrayList<>());
// syncList现在是线程安全的,所有操作都会自动加锁
}
}除了排序,
Collections
binarySearch
reverse
shuffle
fill
max
min
这个问题我个人觉得是很多初学者容易混淆的地方,甚至一些有经验的开发者偶尔也会犯迷糊。简单来说,
Collection
List
Set
ArrayList
HashSet
立即学习“Java免费学习笔记(深入)”;
而
Collections
final
Collection
Collection
Collection
Collections
在多线程环境下,直接使用
ArrayList
HashMap
Collections
synchronizedList()
synchronizedSet()
synchronizedMap()
import java.util.*;
public class SynchronizedCollectionsDemo {
public static void main(String[] args) throws InterruptedException {
List<String> nonSyncList = new ArrayList<>();
List<String> syncList = Collections.synchronizedList(nonSyncList); // 包装成线程安全的
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
syncList.add(Thread.currentThread().getName() + "-" + i);
}
};
Thread t1 = new Thread(task, "Thread-1");
Thread t2 = new Thread(task, "Thread-2");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("同步列表大小: " + syncList.size()); // 理论上应该是2000
// 如果不用synchronizedList,结果可能小于2000,且会抛出ConcurrentModificationException
}
}这些包装器的工作原理很简单,它们返回一个新的集合实例,这个实例的每一个方法(如
add
remove
get
synchronized
hasNext()
next()
synchronized (syncList) {
for (String item : syncList) {
System.out.println(item);
}
}这一点非常重要,不然即使使用了同步包装器,也可能在迭代时遇到
ConcurrentModificationException
除了那些耳熟能详的排序、查找和同步功能,
Collections
1. nCopies(int n, T obj)
List
UnsupportedOperationException
List<String> fiveApples = Collections.nCopies(5, "Apple");
System.out.println("五颗苹果: " + fiveApples); // [Apple, Apple, Apple, Apple, Apple]
// fiveApples.add("Orange"); // 运行时会报错2. emptyList()
emptySet()
emptyMap()
List<Object> emptyList = Collections.emptyList();
Set<String> emptySet = Collections.emptySet();
Map<Integer, String> emptyMap = Collections.emptyMap();
System.out.println("空列表是否为空: " + emptyList.isEmpty()); // true
// emptyList.add("something"); // 运行时会报错3. singletonList(T obj)
singleton(T obj)
singletonMap(K key, V value)
List
Set
Map
new ArrayList(Arrays.asList(obj))
List<String> singleItem = Collections.singletonList("OnlyOne");
System.out.println("单元素列表: " + singleItem); // [OnlyOne]4. disjoint(Collection<?> c1, Collection<?> c2)
true
List<String> list1 = Arrays.asList("A", "B", "C");
List<String> list2 = Arrays.asList("D", "E", "F");
List<String> list3 = Arrays.asList("C", "G", "H");
System.out.println("list1和list2是否不相交: " + Collections.disjoint(list1, list2)); // true
System.out.println("list1和list3是否不相交: " + Collections.disjoint(list1, list3)); // false5. frequency(Collection<?> c, Object o)
frequency
List<String> fruits = Arrays.asList("Apple", "Banana", "Apple", "Orange", "Apple");
System.out.println("Apple出现的次数: " + Collections.frequency(fruits, "Apple")); // 36. checkedList(List<E> list, Class<E> type)
checkedList
checkedSet
checkedMap
ClassCastException
List rawList = new ArrayList(); // 原始的、未受限的列表
List<String> checkedList = Collections.checkedList(rawList, String.class);
checkedList.add("Hello");
// checkedList.add(123); // 运行时会抛出ClassCastException,因为123不是String
System.out.println("Checked List: " + checkedList);这些功能虽然可能不常用,但在需要时能显著提升代码的健壮性和简洁性。
Collections
以上就是如何在Java中使用Collections工具类的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号