当前位置:  开发笔记 > 编程语言 > 正文

如何正确添加数组?

如何解决《如何正确添加数组?》经验,为你挑选了1个好方法。

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

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

我收到一些错误,如下所示,

myTest.java:192: error: no suitable constructor found for HashSet(List)
    Set set = new HashSet(Arrays.asList(arr));
                       ^
constructor HashSet.HashSet(Collection) 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 conforms to int)
 where T is a type-variable:
T extends Object declared in method 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 set = new HashSet( );
Collections.addAll(set, arr);

如何正确地将一个Integer数组添加到Set中?谢谢.



1> Elliott Fris..:

您需要使用包装器类型 Arrays.asList(T...)

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

手动添加元素

int[] arr = { 2, 6, 4, 2, 3, 3, 1, 7 };
Set set = new HashSet<>();
for (int v : arr) {
    set.add(v);
}

最后,如果您需要保留广告订单,则可以使用LinkedHashSet.

推荐阅读
农大军乐团_697
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有