创建一个类的实例并将其添加到地图。爪哇

时间:2020-03-23 13:11:21

标签: java class dictionary instance

好的,可以说我有两个课。顾客和商店。

  // 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<>()
}

我的问题是:

在shop类中,我必须创建一个名为addCustomer的方法,该方法带有4个参数。它将首先创建一个客户实例,然后将其添加到我的地图中,名为客户。

参数不能更改,我的问题是,当方法中的参数与客户类中的变量不同时,如何创建实例感到困惑

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

如何创建实例并将其添加到以memNo为键的客户引用的地图中?

然后,如果我正在测试此方法,则应该可以将客户添加到地图,但是使用此方法addCustomer

谢谢

1 个答案:

答案 0 :(得分:0)

只需创建带有4个参数的addCustomer方法,然后在该方法内部实例化一个新的Customer对象,然后在地图中放入相关的

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