Java集合框架核心分类与特性
集合顶层接口
Collection与Map体系
Java集合框架中Collection和Map是两大独立根接口。所有集合类均位于java.util包。
Collection接口继承Iterable接口,支持增强for循环遍历:
// 遍历Collection示例
for (Element item : collection) {
System.out.println(item);
}
Map虽未直接继承Iterable,但提供三种可迭代视图:
keySet()返回键集合values()返回值集合entrySet()返回键值对集合
单列集合实现类
List体系
ArrayList
基于动态数组实现,初始容量10,扩容因子1.5:
// 扩容机制伪代码
if (size >= capacity) {
newCapacity = oldCapacity + (oldCapacity >> 1); // 1.5倍
copyElements(newCapacity);
}
特点:随机访问O(1),尾部操作高效,线程不安全
LinkedList
基于双向链表实现,节点结构:
class Node<T> {
T data;
Node<T> prev;
Node<T> next;
}
特点:头尾插入删除O(1),随机访问O(n)
CopyOnWriteArrayList
写时复制实现线程安全:
// 写入操作示例
public void add(T element) {
lock.lock();
try {
Object[] newArray = Arrays.copyOf(array, array.length + 1);
newArray[array.length] = element;
array = newArray;
} finally {
lock.unlock();
}
}
Queue体系
ArrayDeque
循环数组实现双端队列,初始容量16,支持首尾高效操作
PriorityQueue
基于二叉堆实现优先级队列:
// 自定义优先级示例
PriorityQueue<Task> queue = new PriorityQueue<>(
Comparator.comparingInt(Task::getPriority)
);
BlockingQueue
阻塞队列实现类包括:
ArrayBlockingQueueLinkedBlockingQueueSynchronousQueue
Set体系
HashSet
基于HashMap实现,哈希冲突解决方案:
// 哈希桶结构示例
Node<K,V>[] table = new Node[INIT_CAPACITY];
// 冲突时形成链表/树
if (collision) {
node.next = new Node(key, value);
}
LinkedHashSet
通过双向链表维护插入顺序
TreeSet
基于红黑树实现有序集合,操作复杂度O(log n)
双列集合实现类
HashMap
数组+链表/红黑树结构,负载因子0.75
ConcurrentHashMap
分段锁实现线程安全:
// JDK7分段锁伪代码
class Segment<K,V> extends ReentrantLock {
volatile HashEntry<K,V>[] table;
}
TreeMap
基于红黑树实现有序映射,支持范围查询
Properties
配置处理专用类,方法示例:
// 加载配置文件
Properties config = new Properties();
config.load(new FileInputStream("app.cfg"));
String value = config.getProperty("key");