如何正确地将数组添加到Set中?

问题描述 投票:0回答:4

我正在尝试将整数数组添加到 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中?谢谢。

java set
4个回答
23
投票

需要使用包装类型才能使用

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


4
投票

从 Java 8 开始,您可以使用 Stream。

int[] arr = { 2, 6, 4 , 2, 3, 3, 1, 7 };

Set<Integer> set = Arrays.stream(arr).boxed().collect(Collectors.toSet());

这应该有效。


3
投票

myTest.java:192: error: no suitable constructor found for HashSet(List<int[]>)

请注意,java 中的数组是

Objects
,因此
Arrays.asList(int[])
将在内部将
int[]
视为单个元素。因此,
<T> List<T> asList(T... a)
将创建
List<int[]>
而不是
List<Integer>
,因此您无法从数组集合(而不是
Set<Integer>
元素)创建
Integer

可能的解决方案是,只需使用

Integer
(包装类)而不是
int
(原始类型)。(这已经由
Elliott Frisch
说明)。

如果您正在使用

Java-8
并获得
int[]
并且无法更改为
Integer[]
,

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

此外,正如

Louis Wasserman
所指出的,如果您使用
java-8
,您可以直接将数组元素收集到
Set

Set<Integer> set = Arrays.stream(arr).boxed().collect(Collectors.toSet());

2
投票

您尝试插入

Set
int
值,但您的
Set
存储
Integer

改变

int[] arr = { 2, 6, 4, 2, 3, 3, 1, 7 };

Integer[] arr = { 2, 6, 4, 2, 3, 3, 1, 7 };

此外,当您要从整数数组中创建集合时,请记住,整数对于范围

-127 to +128
之间的整数有一个特殊的缓存池。值在此范围内的所有 Integer 对象都引用池中的相同对象。因此,不会为集合中的整数分配新的内存。

© www.soinside.com 2019 - 2024. All rights reserved.