java - HashSet add(Object o) 错误

标签 java generics hashset

我试图按如下方式初始化 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/

相关文章:

java - 为什么 Hibernate 将架构名称添加到 Hsql 函数中?

java - 使用通用类型实现相同的功能

delphi - 我可以在 Delphi 中创建特定接口(interface)的通用列表吗?

java - 将我的 HashSet 显示到 ListView

java - 如何在 Android 中将 Hashset 保存到文件?

Java:溢出和打印两次

java - 确保 Spring Quartz 作业执行不重叠

java - 为什么编译错误: “illegal start of type public static double” ?

typescript - 如何将 JSDoc 与通用 typescript 一起使用?

java - 公开 keySet() 的线程安全方式