当我想将项目添加到预定义的Hashtable时,通常很简单。但是,每当我想定义诸如addNewCustomer()
之类的方法并尝试在该方法内使用customerHashtable.put(...);
函数时,它就不起作用。请帮助我定义一种可与现有标签合作的方法,让我在其中添加新对象(客户)。
这是以下代码:
public static void main(String[] args) {
Hashtable<Integer, Customer> customerHashtable = new Hashtable<Integer, Customer>();
customerHashtable.put (1, new Customer("david", "+13035003433", new Address("AR", "77555")));
Customer customer = new Customer("mark", "13035003433", new Address("AR", "77200"));
public void addNewCustomers(int key, Customer customer) {
customerHashtable.put(key, customer);
System.out.println(customerHashtable.get(key).toString());
}
}
}
您必须将addNewCutomers()
方法放在main
方法之外,并为HashTable
创建一个类字段。假设您对静态上下文还可以,则可以看起来像这样:
public class HashtableDemo {
static Hashtable<Integer, Customer> customerHashtable;
public static void main(String[] args) {
customerHashtable = new Hashtable<Integer, Customer>();
customerHashtable.put (1, new Customer("david", "+13035003433", new Address("AR", "77555")));
Customer customer = new Customer("mark", "13035003433", new Address("AR", "77200"));
addNewCustomers(2, customer);
}
public static void addNewCustomers(int key, Customer customer) {
customerHashtable.put(key, customer);
System.out.println(customerHashtable.get(key).toString());
}
}