Hi all,
This is a trivial programming question. I am not an expert in Java. Say I use objects of custom classes Company and Employee, in a manner similar to what many RDBMS examples do:
class Employee
{
Company company;
}
class Company
{
String name;
}
I need to guarantee that different Company objects have unique names - i.e. no two such objects may have the same name, because from my point of view it makes no sense, and also simply eats memory - if two employees work at IBM, then there is a single Company object with that name, period.
My thoughts right now go along of making Company constructor private - so that the job of allocating Company objects with arbitrary names is delegated to a trusted method - which, suppose, will reject any subsequent attempt to create an object with a name that already exists or return an existing or new object (creating one if necessary).
The problem is, I am not sure how to accomplish this elegantly. One thing that would be nice is not having to do a O(n) lookup every time an Company object with a name is requested - so maybe a hash map or a binary tree is there for my convenience? I would also like to override the way the Company objects are identified - which leads me to this: will I be overriding Object.equals and/or Object.hashCode methods?