如何定义一个方法来向java中的现有哈希表输入新项?

时间:2017-09-25 23:04:44

标签: java methods hash 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());
           }
    }

}

1 个答案:

答案 0 :(得分:0)

您必须将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());
    }
}