Java 中 Set 接口详解:特性、用法与常见坑点
一、什么是 Set?
Set 是 Java 集合框架中的一个接口,它继承自 Collection,用于存储不重复的元素。
一句话概括 Set:
Set 是一个 不允许重复元素、通常不关心顺序 的集合。
Set 的核心特性(面试高频)
- 元素唯一性
- 不允许存储重复元素
- '重复'的判断依赖于
equals()(以及某些实现中的hashCode())
- 最多只存在一个 null
- 接口层面允许
null - 是否支持、支持几个,由具体实现决定(这里只记结论即可)
- 接口层面允许
- 无索引、不可通过下标访问
- 没有
get(int index) - 只能通过迭代器或增强 for 遍历
- 没有
二、Set 的基本使用方式
1. 声明与创建
Set<Integer> set = new HashSet<>();
⚠️ 注意:Set 是接口,不能直接 new Set()
三、Set 能存哪些数据类型?
1. 不能使用基本类型
Set 的泛型参数 必须是引用类型,不能是基本类型。
// ❌ 编译错误
// Set<int> set = new HashSet<>();
2. 基本类型 → 包装类型对照表(必背)
int -> Integer
char -> Character
boolean -> Boolean
byte -> Byte
short -> Short
long -> Long
float -> Float
double -> Double
3. 常见可用类型示例
// 包装类型
Set<Integer> intSet = new HashSet<>();
Set<Character> charSet = new HashSet<>();
// 字符串
Set<String> strSet = new HashSet<>();
// 自定义对象
Set<MyClass> objSet = new <>();
Set<List<String>> listSet = <>();
Set<Set<Integer>> setOfSets = <>();


