gpt4 book ai didi

java - 如何正确地将数组添加到集合中?

转载 作者:搜寻专家 更新时间:2023-10-31 08:16:39 25 4
gpt4 key购买 nike

我正在尝试将 Integer 数组添加到 Set 中,如下所示,

int[] arr = { 2, 6, 4 , 2, 3, 3, 1, 7 }; 
Set<Integer> set = new HashSet<Integer>(Arrays.asList(arr));

我收到如下错误提示,

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

其次,我也尝试如下,但仍然出现错误,

int[] arr = { 2, 6, 4 , 2, 3, 3, 1, 7 }; 
Set<Integer> set = new HashSet<Integer>( );
Collections.addAll(set, arr);

如何在 Java 中正确地将 Integer 数组添加到 Set 中?谢谢。

最佳答案

需要使用wrapper类型才能使用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 .

关于java - 如何正确地将数组添加到集合中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34478006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com