You should do more research into the standard Java collections, as you seem a bit confused about what you want, and you seem to be fixated on the old Hashtable
class and its internal implementation.
The theory behind a map, which is what both the old Hashtable
and the modern HashMap
are, is that it maps from a specific key to a single value. The map either contains a key or does not. If it does contain a key, you can get the value associated with the key.
The way in which the hash table operates should be opaque to you. A flat list of key->value pairs could be searched and you'd get the same result. The hash table improves on the speed of this operation by using a hash code, which can be literally any number, provided it's consistently the same number for the same key. It doesn't matter if more than one different key has the same hash code, because the table uses .equals
on potential keys in the table to make sure it got exactly the right one. But the more specific the hash code, the less likely there is to be more than one key to check.
You should be more concerned with what you want to store, what you want to retrieve. Do you want to look up accounts by their account number? Do you want to look up accounts by who owns them? You need to design your data structures in response to that need.
For example, to handle looking up which accounts a person has (and a person can have more than one account), you could make a Map
that maps from a Person
(the key) to a set of Account
s:
final Map<Person, Set<Account>> accountsByPerson = new HashMap<>();
// add account acc1 for a person per1
Set<Account> accountsForThisPerson = accountsByPerson.get(per1);
if (accountsForThisPerson == null) {
accountsForThisPerson = new HashSet<>();
accountsByPerson.put(per1, accountsForThisPerson);
}
accountsForThisPerson.add(acc1);
// retrieve one person's accounts:
final Set<Account> accountsOfPerson1 = accountsByPerson.get(per1);
if (per1 == null) {
System.out.println(per1 + " has no accounts");
}
else {
System.out.println(per1 + " has " + accountsOfPerson1.size() + " account(s)");
for (final Account a : accountsOfPerson1) {
System.out.println(perl + " has account " + a);
}
}
This code presumes that both Account
and Person
implement an equals
and hashCode
method that always gives the right answer: if I have two different objects that represent the same account, equals
says they are the same and hashCode
gives the same result for both of them, and once I put them into a structure like a HashMap or HashSet, their hashCode
does not change.