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 楼答案
您对映射的声明放错了位置,它当前对
findCustomer
和deleteCustomer
方法不可见。这两种方法中没有编译错误吗您应该将其声明为3个方法上方的字段,如下所示:
另外,请注意,将所有内容置于静态可能并不明智,尤其是当您开始使用状态时