简体   繁体   English

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

[英]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.在 shop 类中,我必须创建一个名为 addCustomer 的方法,它带有 4 个参数。 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?如何创建实例并将其添加到客户以 memNo 为键引用的映射中?

Then, if I am testing this method, I should be able to add customers to the map but using this method addCustomer然后,如果我正在测试此方法,我应该能够将客户添加到地图但使用此方法 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 .这可以通过简单地创建一个带有 4 个参数的方法 addCustomer 来完成,然后在该方法内部实例化一个新的 Customer 对象,并使用相关的其放入映射中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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