How to add an Array into Set properly?(如何正确地将数组添加到 Set 中?)
问题描述
我正在尝试将整数数组添加到 Set 中,如下所示,
I'm trying to add in Integer array into Set as following,
int[] arr = { 2, 6, 4 , 2, 3, 3, 1, 7 };
Set<Integer> set = new HashSet<Integer>(Arrays.asList(arr));
我收到一些错误提示,如下所示,
I'm getting some error telling as following,
myTest.java:192: error: no suitable constructor found for HashSet(List<int[]>)
Set<Integer> set = new HashSet<Integer>(Arrays.asList(arr));
^
constructor HashSet.HashSet(Collection<? extends Integer>) is not applicable
(argument mismatch; inferred type does not conform to upper bound(s)
inferred: int[]
upper bound(s): Integer,Object)
constructor HashSet.HashSet(int) is not applicable
(argument mismatch; no instance(s) of type variable(s) T exist so that List<T> conforms to int)
where T is a type-variable:
T extends Object declared in method <T>asList(T...)
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
其次,我也尝试了以下,但仍然出现错误,
Secondly, I also tries as following and still getting error,
int[] arr = { 2, 6, 4 , 2, 3, 3, 1, 7 };
Set<Integer> set = new HashSet<Integer>( );
Collections.addAll(set, arr);
如何在 Java 中正确地将整数数组添加到 Set 中?谢谢.
How to add an Integer array into Set in Java properly ? Thanks.
推荐答案
需要使用wrapper类型才能使用Arrays.asList(T...)
You need to use the wrapper type to use Arrays.asList(T...)
Integer[] arr = { 2, 6, 4, 2, 3, 3, 1, 7 };
Set<Integer> set = new HashSet<>(Arrays.asList(arr));
或手动添加元素,如
int[] arr = { 2, 6, 4, 2, 3, 3, 1, 7 };
Set<Integer> set = new HashSet<>();
for (int v : arr) {
set.add(v);
}
最后,如果需要保留插入顺序,可以使用 LinkedHashSet
.
Finally, if you need to preserve insertion order, you can use a LinkedHashSet
.
这篇关于如何正确地将数组添加到 Set 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何正确地将数组添加到 Set 中?
基础教程推荐
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01