最简洁高效的方式是用ArrayList构造方法传入HashSet,即new ArrayList(hashSet),时间复杂度O(n),不改变原HashSet;注意HashSet无序,转换后顺序不固定。

直接用 ArrayList 的构造方法传入 HashSet 即可完成转换,这是最简洁、高效的方式。
使用 ArrayList 构造器(推荐)
这是最常用也最推荐的做法。ArrayList 提供了接收 Collection 类型参数的构造方法,而 HashSet 实现了 Collection 接口:
- 语法简单:`new ArrayList(hashSet)`
- 时间复杂度为 O(n),内部逐个添加元素
- 不改变原 HashSet,线程安全(仅指操作本身无副作用)
示例代码:
HashSet<string> set = new HashSet();
set.add("apple");
set.add("banana");
set.add("cherry");
ArrayList<string> list = new ArrayList(set); // ✅ 直接转换
</string></string>
使用 Collections.addAll()(需先创建空 ArrayList)
适用于需要复用已有 ArrayList 或在添加前做其他初始化的场景:
- 先 new 一个空 ArrayList,再调用
Collections.addAll(list, set.toArray()) - 注意:
set.toArray()返回 Object[],泛型需手动处理或用set.toArray(new String[0]) - 相比构造器略繁琐,一般不优先选用
注意事项
- HashSet 无序,转换后的 ArrayList 元素顺序不固定(不保证与插入顺序一致)
- 若需保持插入顺序,应改用 LinkedHashSet 而非 HashSet
- 转换后两个集合互不影响:修改 ArrayList 不影响 HashSet,反之亦然
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











