如何正确地将数组添加到Set中? [英] How to add an Array into Set properly?

查看:57
本文介绍了如何正确地将数组添加到Set中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Integer数组添加到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));

我收到以下错误提示,

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中正确将Integer数组添加到Set中?谢谢.

How to add an Integer array into Set in Java properly ? Thanks.

推荐答案

您需要使用包装器类型才能使用 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中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆