当前位置: 首页 > 面试题库 >

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

朱运诚
2023-03-14
问题内容

我正在尝试将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中?谢谢。


问题答案:

您需要使用包装器类型才能使用 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



 类似资料:
  • 问题内容: 现在我将数组作为字符串添加到正文中: 但是服务器需要在post参数上使用数组。如何添加数组而不是字符串?okhttp可以吗? 问题答案: 您当前正在以字符串形式发布。您将要模仿POST的复选框形式,用于 更多信息和良好的阅读, https://teamtreehouse.com/community/how-to-handle-multiple-checkboxes-values-in-

  • 我试图向数组中添加一个元组(例如,2项元组)。 我得到的是: 找不到接受提供的参数的“=”的重载 提示:我试图超载每个参考书的=: ...但是没有弄对。 有什么想法吗。。。解决方案

  • 因此,对于我的学校项目,我们将使用SQL数据库,并在JFrame面板上显示值。 为了在JTable中显示数据,我们必须要求下一个语法:(def)

  • 问题内容: 如何将对象添加到数组(使用javascript或jquery)?例如,此代码有什么问题? 我想使用此代码在function1数组中保存许多对象,并调用function2在数组中使用该对象。 如何将对象保存在数组中? 如何将对象放入数组并将其保存到变量? 问题答案: 使用Array.push()将任何东西放入数组。 有关数组的更多信息 一次添加多个项目 将项目添加到数组的开头 将一个数组

  • 问题内容: 我正在尝试向从创建的数组中添加一列。在这种情况下,它是一个数组:(行,列)。 我想添加第九列。空或零都无所谓。 问题答案: 我认为您的问题是您希望就地添加该列,但是由于存储的numpy数据的原因,它的作用是创建连接数组的副本 所以你需要保存输出: 替代方式: 我相信这三个函数(以及)之间的唯一区别是未指定when的默认行为: 假设 假设除非输入为1d,否则 如果输入为1d,则假定在添加

  • 我将apache poi的jar文件添加到项目的构建路径中,但在尝试XWPFDocument docx=new XWPFDocument(new FileInputStream(folderName+fileName))时仍然出现错误; 我尝试添加不同版本的Apache POI的jar文件,但没有成功。如果没有JSP环境,我的程序也可以工作。 这是我的错误消息:org.apache.catalin