HashSet add(Object o)错误

时间:2015-12-06 07:03:59

标签: java generics hashset

我试图按如下方式初始化一个HashSets数组并且它没有找到适合添加(整数)"的方法,我试图明确地添加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声明)不是最佳做法,因为它失去了类型检查能力,还有更好的方法来执行上述操作吗?

2 个答案:

答案 0 :(得分:2)

这是一种方法:

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

答案 1 :(得分:1)

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

相关问题