0

Hi I am using HashMap to add, find and remove Customers. I want them to be in separate classes to use the concept of divide-and-conquer, but I am failing to find and remove the customers. I was even suggested to loop the findCustomer to retrieve all the details.

  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
    Your customers map in your addCustomer certainly shadow the static one you defined elsewhere. Commented Apr 17, 2014 at 13:03

1 Answer 1

1

Your declaration of your map is misplaced, it is not currently visible to findCustomer and deleteCustomer methods. Don't you have a compile error in these 2 methods?

You should declare it as a field above the 3 methods, like this:

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

Also, note that putting everything static might not be wise, especially if you start working with a state.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, you should remove all these static keywords and use an instance of the class instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.