【发布时间】:2018-08-24 03:10:44
【问题描述】:
我的问题是,我如何“解包”一个 hashmap 值对象?
我能够创建、保存和加载哈希图。我正在做一个填充然后选择员工来计算工资。
Map<Integer, Employee> hm = new HashMap<>();
hID++;
System.out.println("Enter employee first name: ");
String nameF = sc.next();
System.out.println("Enter employee last name");
String nameL = sc.next();
hourly = new HourlyEmployee();
Employee hEmp = new Employee(hourly, nameF, nameL);
System.out.println(hEmp.getName());
hm.put(hID, hEmp);
/*
save()
exit
run
load()
select employee, enter ID
loops to find match
*/
Set<Map.Entry<Integer, Employee>> set = hm.entrySet();
do
{
System.out.println("Enter the empoyee ID");
int id = sc.nextInt();
if (id >= 1000 && id < 1999)
{
System.out.println("***** HOURLY *****");
for (Map.Entry<Integer, Employee> entry : set)
{
if (entry.getKey().equals(id))
{
// this is where I run into the issues. all I get
// with the value is the hash location. I can't
// figure out how to unwrap into the hourly class
// as the object, then edit the values then wrap again.
System.out.println(entry.getValue());
// I understand this is not how you get what I
// need. But this does give me:
//
// "edu.umsl.composition.++++++++.Employee@682a0b20"
}
}
查看代码 cmets。
【问题讨论】:
-
值没有发生奇怪的“包装”。 Any Employee 会这样打印,不管 HashMap 值与否,因为您没有编写 toString 方法。像往常一样使用对象。
-
我想说的是类 HourlyEmployee 是 Employee 的一部分,没有继承。我希望能够访问 HourlyEmployee 方法
-
在不涉及 HashMap 的情况下做任何你想做的事情。 (另外,你的班级构成没有任何意义。)
-
那没用。什么没有意义?我正在尝试学习。这是来自 3 个不同类的部分代码。 Main Class(主要方法和菜单) Employee Class > 1. Hourly Class 2. Salary Class 3. Commission Class
-
我可以访问 Employee 方法,但不能访问 HourlyEmployee 方法