目标:掌握高级集合的使用场景。
Set:HashSet 与 TreeSet
特性 | HashSet |
TreeSet |
底层实现 | 基于HashMap实现,元素存储在哈希表中 | 基于红黑树实现,元素按照自然顺序排序 |
元素顺序 | 无序 | 按自然顺序或指定比较器排序 |
时间复杂度 | 插入、删除、查找操作时间复杂度为 O(1) | 插入、删除、查找操作时间复杂度为 O(log n) |
是否允许为null | 允许存储一个null元素 | 不允许存储null元素 |
适用场景 | 快速查找,判断元素是否存在 | 需要有序存储元素或按自定义顺序访问元素 |
无序和不重复实现原理 :
- HashSet:依赖
hashCode()
和equals()
方法,确保元素唯一性和高效查找。 - TreeSet:通过红黑树结构和比较器(
Comparable
或Comparator
)保证元素唯一性和排序。
import java.util.HashSet;
import java.util.Set;
public class HashSetDemo {
public static void main(String[] args) {
Set<String> hashSet = new HashSet<>();
// 添加元素
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Cherry");
hashSet.add("Apple"); // 重复元素不会被添加
// 遍历
System.out.println("HashSet Elements:");
for (String item : hashSet) {
System.out.println(item);
}
}
}
import java.util.Set;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
Set<String> treeSet = new TreeSet<>();
// 添加元素
treeSet.add("Dog");
treeSet.add("Cat");
treeSet.add("Elephant");
treeSet.add("Dog"); // 重复元素不会被添加
// 遍历
System.out.println("TreeSet Elements (Sorted):");
for (String item : treeSet) {
System.out.println(item);
}
}
}
线程安全集合
ConcurrentHashMap
的特点。- 高并发环境下的性能优化:
- 基于分段锁机制(Java 8之前),提高并发访问性能。
- Java 8起采用
CAS
(无锁操作)和红黑树,提高查询和插入效率。
- 线程安全:
- 允许多个线程并发访问,不需要外部同步。
- 对比:
- 高并发环境下的性能优化:
特性 | HashMap | ConcurrentHashMap |
线程安全 | 否 | 是 |
性能(单线程) | 高 | 低 |
性能(多线程) | 低 | 高 |
允许null键和值 | 允许一个null键 | 不允许 |
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;
public class ConcurrentHashMapDemo {
public static void main(String[] args) {
Map<String, Integer> concurrentMap = new ConcurrentHashMap<>();
// 添加元素
concurrentMap.put("Key1", 1);
concurrentMap.put("Key2", 2);
concurrentMap.put("Key3", 3);
// 遍历
System.out.println("ConcurrentHashMap Elements:");
concurrentMap.forEach((key, value) ->
System.out.println("Key: " + key + ", Value: " + value)
);
// 并发操作示例
Runnable task = () -> concurrentMap.merge("Key1", 1, Integer::sum);
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
thread1.start();
thread2.start();
}
}
使用建议
选择合适集合
-
Set
:- 使用
HashSet
进行快速查重。 - 需要排序时使用
TreeSet
。
- 使用
-
Map
:- 单线程环境下可以使用
HashMap
。 - 多线程环境下优先使用
ConcurrentHashMap
。 - 需要有序输出时使用
TreeMap
。
- 单线程环境下可以使用
性能优化
- 在处理大数据量时,为集合设置初始容量,减少扩容带来的性能损耗。
- 在多线程环境中,避免使用全局锁,通过分段锁或无锁操作优化性能。
总结
本文讲解了 Java 高级集合的特性与使用场景:
- HashSet:基于哈希表,元素无序,允许一个
null
,操作复杂度O(1)
。 - TreeSet:基于红黑树,元素有序,不允许
null
,操作复杂度O(log n)
。 - ConcurrentHashMap:多线程安全,采用分段锁或无锁操作,不允许
null
键和值。
建议:
- 快速查重用 HashSet,需要有序用 TreeSet。
- 单线程用 HashMap,多线程用 ConcurrentHashMap。