一、集合体系总览
Java 集合根接口:Collection(单列集合,存一个个对象)两大分支:
- List:有序、可重复、有索引
- Set:无序、不重复、无索引
工具类:Collections:操作集合的静态工具方法
二、Collection 集合
1. 特点
- 所有单列集合的根接口
- 定义了所有单列集合共有的方法
- 不能直接创建对象,只能使用实现类(ArrayList、HashSet 等)
2. 常用方法(所有 List/Set 都能用)
// 添加元素
collection.add("张三");
// 清空集合
collection.clear();
// 删除指定元素
collection.remove("张三");
// 判断是否包含某个元素
collection.contains("张三");
// 判断是否为空
collection.isEmpty();
// 获取集合大小
collection.size();
// 转成数组
collection.toArray();
3. Collection 遍历方式(3 种)
-
迭代器遍历(通用)
Iterator
it = list.iterator();
while(it.hasNext()){
String s = it.next();
} -
增强 for 循环(最常用)
for(String s : collection){
System.out.println(s);
} -
forEach 方法(Lambda)
collection.forEach(s -> System.out.println(s));
三、List 集合(有序、可重复、有索引)
1. 特点
- 存取有序
- 元素可重复
- 有索引,可以通过索引操作
2. 常用实现类
- ArrayList:底层数组,查询快、增删慢
- LinkedList:底层链表,查询慢、增删快(可做队列、栈)
3. List 特有方法(带索引)
// 在指定索引插入元素
list.add(2, "李四");
// 根据索引删除
list.remove(2);
// 修改指定索引元素
list.set(1, "王五");
// 根据索引获取元素
list.get(0);
4. List 遍历方式(4 种)
- 普通 for 循环(利用索引)
- 迭代器
- 增强 for
- Lambda forEach
四、Set 集合(无序、不重复、无索引)
1. 特点
- 存取无序
- 元素唯一,不能重复
- 没有索引,不能用普通 for 遍历
2. 常用实现类
- HashSet:最常用,底层哈希表,无序、不重复
- LinkedHashSet :底层哈希表 + 链表,有序、不重复
- TreeSet :底层红黑树,可排序、不重复
3. HashSet 去重原理(面试高频)
- 先调用 hashCode() 计算哈希值
- 哈希值相同,再调用 equals() 比较内容
- 都相同 → 判定重复,不存入
注意 :自定义对象要存在 HashSet 中,必须重写 hashCode () 和 equals ()
4. TreeSet 排序规则
- 对元素自动排序
- 两种排序方式:
- 自然排序 :元素类实现
Comparable接口 - 比较器排序 :创建集合时传入
Comparator
- 自然排序 :元素类实现
五、Collections 工具类
1. 作用
专门用来操作 Collection 集合的静态工具类
2. 常用方法
// 批量添加多个元素
Collections.addAll(list, "a", "b", "c");
// 打乱顺序(只对 List 有效)
Collections.shuffle(list);
// 排序(默认升序)
Collections.sort(list);
// 自定义排序(比较器)
Collections.sort(list, (o1, o2) -> o2 - o1);
// 获取最大值
Collections.max(list);
// 获取最小值
Collections.min(list);
// 反转集合
Collections.reverse(list);
六、面试题题总结
- List 和 Set 的区别
- List:有序、可重复、有索引
- Set:无序、不重复、无索引
- ArrayList 和 LinkedList 区别
- ArrayList:数组,查询快
- LinkedList:链表,增删快
- HashSet 如何保证去重
- hashCode() + equals()
- Collections 和 Collection 的区别
- Collection:根接口
- Collections:操作集合的工具类
总结
- Collection:单列集合根接口,定义通用方法
- List:有序、可重复、有索引(ArrayList/LinkedList)
- Set:无序、不重复、无索引(HashSet/LinkedHashSet/TreeSet)
- Collections:集合工具类,提供排序、打乱、批量添加等静态方法