java - 尝试从列表构造 HashSet<Integer> 时参数不匹配 - 为什么?

标签 java compiler-errors set

这个问题在这里已经有了答案:





How to create ArrayList (ArrayList<Integer>) from array (int[]) in Java

(5 个回答)



How to convert int[] into List<Integer> in Java?

(20 个回答)


3年前关闭。




所以,我一直在这个名为 Codewars 的网站上做一个在线代码问题,我的代码有一些问题。当我使用设置界面时,它给了我一个错误:

/workspace/java/src/FindOdd.java:16: error: no suitable constructor found for HashSet(List<int[]>)
    Set<Integer> keys = new HashSet<Integer>(Arrays.asList(a));
                        ^
    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: /workspace/java/src/FindOdd.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

(顺便说一句,我的代码还没写完,告诉我要不要先写完)

这是我的代码:
import java.util.*;

public class FindOdd {
  public static int findIt(int[] arr) {
    LinkedHashMap apearanceCount = new LinkedHashMap();

    for(int i = 0; i < arr.length; i++){
      if(apearanceCount.containsKey(arr[i])){
        int amount = Integer.parseInt(apearanceCount.get(arr[i]).toString()) + 1;
        apearanceCount.put(arr[i], amount);
      } else {
        apearanceCount.put(arr[i], 1);
      }
    }

    Set<Integer> keys = new HashSet<Integer>(Arrays.asList(arr));
  }
}

请帮我!

(对于认为这是重复的人,据我所知,数组转换为集合与将数组转换为列表不同。如果我错了,请在评论中回答。;))

最佳答案

错误是 HashSet类没有采用接口(interface) List 的构造函数.但是,它确实有 Collection 的构造函数。界面。所以试试new ArrayList<>(Arrays.asList(arr)) .

关于java - 尝试从列表构造 HashSet<Integer> 时参数不匹配 - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52013707/

相关文章:

java - 这个程序如何在不知道数据类型的情况下接受数据?

c# - C#-为什么我不能在另一个类中更改int变量?

c++ - 是否有支持 insert() 等的 sorted_vector 类?

c++ - GCC STL_tree.h std::set 的红黑树源代码

list - 是否值得转换为套装?

java - 使用文本框作为 JList 的输入

java - 二维数组中的第一个元素变为空?

javascript - typescript :使用预先存在的标识符覆盖/扩展 Lib.d.ts

java - Bootstrap jar 定位../lib/rt.jar 和 ../lib/ext.**jar 如何以及何时加载?

angular - 无法成功编译我的 Angular 应用程序