gpt4 book ai didi

java - 使用 HashMap 添加、删除和查找

转载 作者:行者123 更新时间:2023-12-01 13:07:51 26 4
gpt4 key购买 nike

您好,我正在使用 HashMap 添加、查找和删除客户。我希望他们分在不同的类(class),以使用分而治之的概念,但我未能找到并删除客户。我什至建议循环 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"));
}

最佳答案

您的 map 声明放错了位置,目前对 findCustomerdeleteCustomer 方法不可见。这2个方法没有编译错误吗?

您应该将其声明为 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"));
}

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

关于java - 使用 HashMap 添加、删除和查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23133900/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com