【问题标题】:HashSet add(Object o) errorHashSet add(Object o) 错误
【发布时间】:2015-12-06 07:03:59
【问题描述】:

我正在尝试按如下方式初始化一个 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]));
}

有人可以帮助指出我可能做错了什么吗? 此外,使用通配符(即设置声明,因为它失去类型检查能力)不是最佳实践,还有更好的方法来完成上述操作吗?

【问题讨论】:

  • 给出一个通用数组初始化编译错误

标签: java generics hashset


【解决方案1】:

这是一种方法:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-01
      • 1970-01-01
      • 2018-03-12
      • 2021-10-10
      • 1970-01-01
      • 2017-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多