HashSet 添加(对象 o)错误

HashSet add(Object o) error

我正在尝试按如下方式初始化 HashSet 数组,但它抛出了 "no suitable method found for 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 声明,因为它失去了类型检查能力,有更好的方法来执行上述操作吗?

这是一种方法:

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]));
}

为了回答代码中直接错误的问题,adj[pre[i][1]] 具有类型 HashSet<?>,即 unknown 组件类型的 HashSet。您不能向此类类型添加任何内容(null 除外),因为无法保证您添加的任何内容都是此未知类型的实例。