有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 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"));
      }  
    

    另外,请注意,将所有内容置于静态可能并不明智,尤其是当您开始使用状态时