这个问题在这里已经有了答案:
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/