我试图按如下方式初始化 HashSet 数组,但它抛出“找不到适合 add(Integer) 的方法”,我尝试简单地添加 pre[i][0],但这也不起作用。
此外,pre 是 int[][] 类型,numCourses 是 int 类型,pre[i][j] 是 [0,numCourses-1] 的元素。
Set<?>[] adj= new HashSet<?>[numCourses];
for(int i=0; i<numCourses; ++i) adj[i]=new HashSet<Integer>();
for(int i=0; i<numCourses; ++i){
adj[pre[i][1]].add(new Integer(pre[i][0]));
}
有人可以帮我指出我可能做错了什么吗? 此外,使用通配符(即设置声明)不是最佳实践,因为它失去了类型检查能力,还有更好的方法来执行上述操作吗?
最佳答案
这是一种方法:
Set<Integer>[] adj = (Set<Integer>[]) new HashSet[numCourses];
for(int i=0; i<numCourses; ++i) adj[i]=new HashSet<Integer>();
for(int i=0; i<numCourses; ++i){
adj[pre[i][1]].add(new Integer(pre[i][0]));
}
关于java - HashSet add(Object o) 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34114964/