Search code examples
javahashmap

Is it possible to store different instances of the same class in Java with Hashmap?


I have a registration program where users can reserve tables at a restaurant.

Since I need to store potentially endless amount of customers, I cannot explicitly create new instances of my Customer class, because I need to be able to add them at runtime.

I thought about using a HashMap to insert every user through a registration form they fill up, however, rather than keeping the unique values of each Customer, it overwrites them with the latest entry in the hashmap.

To be clear, the key IS changing, it's successfully adding a new key, but the values inside the previous key are overwritten

Example

Class Customer has 3 setters: set Id, set fname, set lname.

These simply take the input from the registration form and assign it to each instance variable.

I create my only instance of the class with Customer cust = new Customer(). And HashMap hm = new HashMap()

User fills up the Form, selects submit. This submit button calls all the setters to assign the info.

I then use hm.put(cust.getId(), cust).

And I am able to correctly retrieve the values with Customer retrieveCust = (Customer) map.get(ID) String fname = retrieveCust.getName()

However, it's only the latest set of values. So If I have John doe and Jane doe, only Jane is retrieved for every key.

Is there a way to make it store every different "instance" of cust, with the values submitted by the Form?


Solution

  • I'm assuming you have something like Map<String, Customer>. The key can only have one value. So, the map will always have the latest value that you assigned to the key.

    If you want to have different values for the key, you should consider something likeMap<String, List<Customer>> or Map<String, Set<Customer>>.