我正在尝试打印出带有整数键和Employee值的树形图。每个Employee对象应包含(字符串)姓氏,(字符串)名字,(整数)ID和(字符串)性能比例。我已经完成了班级员工。但是,我的输出带有值作为位置。
Map(Integer,Employee)e = new TreeMap(Integer,Employee)();
Employee e1 = new Employee("Puppy", "Nguyen", new Integer(345), "4");
e.put(e1.getID(), e1);
Employee e2 = new Employee("Kitty", "Thompsons", new Integer(123), "2");
e.put(e2.getID(), e2);
Employee e3 = new Employee("Cubby", "Gonzalez", new Integer(234), "5");
e.put(e3.getID(), e3);
System.out.println("Original Employee-typed TreeMap: ");
for(Map.Entry<Integer, Employee> entry : e.entrySet())
{
System.out.println("ID: " + entry.getKey());
System.out.println("Employee: " + entry.getValue());
}
我的输出:
原始员工类型的TreeMap:
ID:123
员工:员工@ fef18a5d
ID:234
员工:员工@ ec71836a
ID:345
员工:员工@ 89120ee
答案 0 :(得分:2)
您必须覆盖Employee
中的toString()
方法。现在你正在看
getClass().getName() + '@' + Integer.toHexString(hashCode())
,显然没有太多意义。
@Override
public String toString(){
return this.name; // Or however the local field is declared
}
答案 1 :(得分:0)
Java正在打印Employee对象的类名和内存地址,因为它们没有String toString()方法。实现它以提供员工的描述,并在打印或调试等时使用它。
E.g:
@Override
public String toString() {
return this.getFirstName() + ' ' + this.getLastName() +
" (Perf. Scale: " + this.getPerformanceScale() +')';
}
答案 2 :(得分:0)
你可以这样做
for(Map.Entry<Integer, Employee> entry : e.entrySet())
{
System.out.println("ID: " + entry.getKey());
Employee employee = entry.getValue();
System.out.println("Employee: " + employee.getFirstName() +" "+employee..getLastName());
}
或强>
您需要在Employee类中添加toString()
方法,如下所示
class Employee{
@Override
public String toString() {
return this.firstName + " " + this.lastName;
}
}