【发布时间】:2018-11-14 03:10:38
【问题描述】:
我的 for-each 循环出现此错误:
“类型不匹配:无法从元素类型 Object 转换为 Employee”
private static HashMap<Integer,Employee> employeeDatabase = new HashMap<Integer,Employee>();
public HashMap getEmployeeDatabase() {
return employeeDatabase;
}
for(Employee e: c.getEmployeeDatabase().values())
{
e.print();
}
如果重要的话 - 'Employee' 包含 int(id)、String(name)、double(salary)。当填充 HashMap 时,复制 int(id) 以用作我的 HashMap 的 Integer 键。
编辑:问题在于 getEmployeeDatabase 访问器返回原始类型,感谢那些回答的人。
对于那些想知道“c”变量的人:
Company c = new Company();
这就是它的来源。 Company 类默认构造函数使用私有方法从 Scanner 填充employeeDatabase。
【问题讨论】:
-
返回类型
HashMap是一个 raw 泛型。不要使用 raw 泛型。指定正确的类型参数,即HashMap<Integer,Employee> -
你能展示你的完整代码吗?
标签: java