使用HashMap添加,删除和查找

时间:2014-04-17 13:02:20

标签: java hashmap

您好我使用HashMap添加,查找和删除Customers。我希望他们在不同的班级中使用分而治之的概念,但我没有找到并删除客户。我甚至建议循环使用findCustomer来检索所有细节。

  public static void addCustomer(){
       // Customers
    Map<String, Customer> customers = new HashMap<> ();
    customers.put ("ID1", new Customer ("Jonathan", "Mifsud", "Test Address", 21345678, "L001"));
    customers.put ("ID2", new Customer ("David", "Aguis", "2nd Address", 21456778, "L002"));
    customers.put ("ID3", new Customer ("Frank", "Mamo", "example Address", 21987653, "L003"));
  }

  public static void findCustomer(){
      //retrieve Customer Details
    System.out.println("Customer with ID1 is " + customers.get("ID1"));
  }

  public static void deleteCustomer(){
      //remove Customer Details
    System.out.println("Customer Deleted is ID3 " + customers.remove("ID3"));
  }  

1 个答案:

答案 0 :(得分:1)

您对地图的声明放错了地方,findCustomerdeleteCustomer方法目前无法看到。你不是在这两种方法中有编译错误吗?

你应该将它声明为3个方法之上的字段,如下所示:

  private static Map<String, Customer> customers = new HashMap<> ();

  public static void addCustomer(){
       // Customers
    customers.put ("ID1", new Customer ("Jonathan", "Mifsud", "Test Address", 21345678, "L001"));
    customers.put ("ID2", new Customer ("David", "Aguis", "2nd Address", 21456778, "L002"));
    customers.put ("ID3", new Customer ("Frank", "Mamo", "example Address", 21987653, "L003"));
  }

  public static void findCustomer(){
      //retrieve Customer Details
    System.out.println("Customer with ID1 is " + customers.get("ID1"));
  }

  public static void deleteCustomer(){
      //remove Customer Details
    System.out.println("Customer Deleted is ID3 " + customers.remove("ID3"));
  }  

另外,请注意,将所有内容置于静态可能并不明智,特别是如果您开始处理状态。