Java 集合框架的体系是什么?List、Set、Queue、Map 有什么区别?
集合框架有两个根:Collection 存单个元素,Map 存键值对,Map 不继承 Collection。Collection 下分三类:List 有序、可重复、按下标访问;Set 不重复;Queue / Deque 按处理顺序存取。实现类的名字说明了结构,如 ArrayList、LinkedHashSet、TreeMap。Collections 是提供排序、包装等方法的工具类。
| 接口 | 特点 | 常用实现 | 底层结构 |
|---|---|---|---|
List |
有序、可重复、按下标访问 | ArrayList / LinkedList |
动态数组 / 双向链表 |
Set |
不重复 | HashSet / LinkedHashSet / TreeSet |
哈希表 / 哈希表 + 链表 / 红黑树 |
Queue / Deque |
队列、双端队列 | ArrayDeque / PriorityQueue |
循环数组 / 二叉堆 |
Map |
键值对,key 不重复 | HashMap / LinkedHashMap / TreeMap |
哈希表 / 哈希表 + 链表 / 红黑树 |
为什么 Map 不继承 Collection:Collection 的 add(E) 存单个元素,Map 存的是键值对,语义不匹配。Map 通过 keySet()、values()、entrySet() 三个视图和 Collection 衔接。
Collection vs Collections:Collection 是接口;Collections 是工具类,提供 sort、unmodifiableList、synchronizedList、emptyList 等静态方法(类似数组的工具类 Arrays)。
遗留类:Vector、Stack、Hashtable 是 Java 1.0 的同步容器,所有方法加锁,新代码不再使用,分别用 ArrayList、ArrayDeque、HashMap / ConcurrentHashMap 代替。
编程面向接口:声明成 List<String> list = new ArrayList<>(),以后换实现不影响调用方。
面试口语版中文 · 约 100 秒
集合框架有两个根接口:Collection 和 Map。Collection 存的是单个元素,下面分三类:List 有序、可以重复、能按下标访问,常用 ArrayList;Set 不允许重复,常用 HashSet;Queue 和 Deque 是按处理顺序存取的队列,常用 ArrayDeque 和 PriorityQueue。Map 存键值对,常用 HashMap,它不继承 Collection,因为 add 一个元素的语义对键值对不成立,但可以通过 keySet、values、entrySet 这三个视图转成集合。
每个接口都有基于不同数据结构的实现,名字基本就说明了结构:ArrayList 是数组,LinkedHashSet 是哈希表加链表,TreeMap 是红黑树。所以选集合,本质是选数据结构。另外 Collections 是一个工具类,提供排序、不可修改包装这些静态方法,和 Collection 接口不是一回事。
English PitchEnglish · ~55s
The Java Collections Framework has two distinct roots: Collection for single elements and Map for key-value pairs—Map doesn't extend Collection because add(E) doesn't fit pairs, though it bridges via keySet(), values(), and entrySet(). Under Collection, List is ordered, indexed, and allows duplicates; Set enforces uniqueness; and Queue/Deque manage elements in processing order. Implementation names tell you the backing structure—ArrayList, LinkedHashSet, TreeMap—so picking a collection is really picking a data structure. In production, I program to interfaces, skip legacy synchronized types like Vector and Hashtable, and keep the Collection interface distinct from the Collections utility class.
Key terms: Collection vs Map, Deque, entrySet, Collections utility class
Likely follow-up: "Why are Vector and Hashtable considered obsolete even in multithreaded code, and what's the most efficient way to iterate over a Map?"
追问3 个
List 和 Set 的区别?
List 有序、可重复、能按下标访问;Set 不允许重复,是否有序取决于实现(HashSet 无序、LinkedHashSet 插入顺序、TreeSet 排序)。
为什么不再用 Vector、Hashtable?
每个方法都加
synchronized,单线程有不必要的开销,多线程下复合操作仍然不安全;需要线程安全时有更好的选择(ConcurrentHashMap、CopyOnWriteArrayList)。遍历 Map 有哪些方式?
entrySet()遍历(同时要 key 和 value 时最好)、keySet()、values()、forEach((k, v) -> ...)。不要遍历keySet()再get(k),多一次查找。
易踩坑
- 说“Map 也是 Collection”,这是最常见的错误。
- 把 HashSet 当前碰巧的遍历顺序当成保证,换 JDK 或元素一多就会变。