因此,我一直在这个名为Codewars的网站上进行在线代码问题,我的代码遇到了一些问题。当我使用set接口时,它给了我一个错误:
/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));
}
}
请帮助我!
(对于那些认为这是重复项的人,据我所知,将数组转换为集合与将数组转换为列表不同。如果我错了,请在评论中回答。;))
答案 0 :(得分:-2)
错误是说HashSet
类没有采用接口 List
的构造函数。但是,它确实具有Collection
接口的构造函数。因此,请尝试new ArrayList<>(Arrays.asList(arr))
。