简体   繁体   中英

Creating an instance of a class and adding it to a map. Java

Okay, lets say I have two classes. A customer and a shop.

  // In the class customer, I have 3 instance variables. 
  private String aFullName; 
  private String address;
  private char age; 

 // Then in the constructor, I have initialised these too:
 this.aFullName = fullName; 
 this.address = anAddress;
 this.age = anAge;

 //In my second class then, the shop...
 //I only have one variable where I've referenced a map: 
 private Map<String, Customer> customers;

//My constructor:
public Shop()
{
super();
customers = new HashMap<>()
}

MY QUESTION IS:

In the shop class, I have to create a method called addCustomer which takes 4 arguments. It will first create an instance of a customer and then add it my map called customers.

The arguments cannot change, my problem is I'm confused as to how to create an instance when the arguments in the method and the variables in the customer class are different

public void addCustomer(String memNo, String name, String address, char ageCat)
// where memNo is going to be the key.

How do I create an instance and add it to the map referenced by customers with memNo as the key?

Then, if I am testing this method, I should be able to add customers to the map but using this method addCustomer

Thank you

This can be done by simply creating a method addCustomer with the 4 parameters and then inside of that method instantiate a new Customer object and put it in the map with the relevant key .

public void addCustomer(String memNo, String name, String address, char ageCat) {
    customers.put(memNo, new Customer(name, address, ageCat);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM