HashMap仅显示最后一个条目

时间:2014-10-09 09:04:15

标签: java hashmap

仅显示HashMap的最后一个条目。 我的hashMap由employee类型的键和类型为hobby的值组成,但在显示时只显示最后一个条目。

请帮我删除此代码中的错误:

public void addEmployees(int a, HashMap<Employee,Hobby> hMap)
{
    Employee emp = new Employee();
    Hobby hob = new Hobby();
    Scanner obj = new Scanner(System.in);
    Scanner obj1 = new Scanner(System.in);

    for(int i =0; i<a ; i++)
    {
        System.out.println("Enter id of employee:");
        int num = obj.nextInt();
        emp.setEmployeeId(num);

        System.out.println("Enter name of employee:");
        String str = obj1. nextLine();
        emp.setName(str);

        hob.enterHobby();
        hMap.put(emp,hob);
    }    
}


public static void main(String [] args)
{
    HashMap <Employee,Hobby> employeeName = new HashMap <Employee,Hobby>();
    System.out.println("Enter the number of employees you want to add");
    Scanner obj = new Scanner(System.in);
    Scanner obj1 = new Scanner(System.in);
    int num = obj.nextInt();
    EmployeeManag emg = new EmployeeManag();
    emg.addEmployees(num,employeeName);
}


class Hobby
{
    ArrayList<String> arr = new ArrayList<String>();

    public void enterHobby()
    {
        Scanner obj1 = new Scanner(System.in);
        System.out.println("Add Hobbie");
        String str = obj1.nextLine();
        arr.add(str);
    }

    public void displayHobbie()
    {
        for(String str : arr)
        {
            System.out.println(str);
        }
    }
}

class Employee
{

    private int employeeId;
    private String name;

    public int getEmployeeId() 
    {
        return employeeId;
    }
    public String getName() 
    {
        return name;
    }
    public void setName(String name) 
    {
        this.name = name;
    }

    public void setEmployeeId(int employeeId) 
    {
        this.employeeId = employeeId;
    }
}

1 个答案:

答案 0 :(得分:3)

为每次迭代在for循环中创建emp对象。

public void addEmployees(int a, HashMap<Employee,Hobby> aList)
        {
           Scanner obj = new Scanner(System.in);
           Scanner obj1 = new Scanner(System.in);

           for(int i =0; i<a ; i++)
             {
                Hobby hob = new Hobby();
                Employee emp = new Employee();
                System.out.println("Enter id of employee:");
                int num = obj.nextInt();
                emp.setEmployeeId(num);

                System.out.println("Enter name of employee:");
                String str = obj1. nextLine();
                emp.setName(str);

                hob.enterHobby();
                hMap.put(emp,hob);
              }    
          }