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

标签 java set

我正在尝试将 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/

相关文章:

java - 上传后从 nexus 插件访问 Sonatype nexus 工件

swift - 将字典数组转换为集合 Swift 4

php - 找到分区集的每个可能组合的更好方法

Java:在 NavigableSet 中添加相同的对象被拒绝

Java 树集排序算法

java - 删除设备所有者 Android

java - 为什么 XPath 从整个文档返回节点,而不仅仅是选择节点

java - java中如何将爬取的数据存储到sql数据库中

Java不渲染显示表

c++ - 在 C++ STL 中使用 set 的删除属性后,以几乎相同的方式获得不同的输出