Reputation: 10285
Let Person be a class with attributes name, age and idNumber. I want to have a collection of "Persons", and I want to be able to perform the following operations in the most efficient way:
My idea is to simultaneously maintain a Hashmap using the id as key and two Treemaps using age and name as keys for each of the TreeMaps.
Upvotes: 2
Views: 1103
Reputation: 340973
Is this the best way?
I would say that using a relational database and proper indexing is the best way, but if you want to do this in-memory, then yes - you are sacrificing memory for performance.
Is it necessary to remove a person from the age TreeMap before editing the age to then put it back in?
Yes. The position of an item in a tree is determined once when it is added. If the comparable property (age
or name
) changes, the TreeMap
won't magically discover that and move the object. This will most likely cause inability to find element in a map even though it's there.
If answer to question 2 is yes, how do I handle that when that persons are being used and potentially being edited on multiple places?
Prefer immutable objects so it is not possible to alter an object already placed in a tree. If for any reason you can not afford for that, consider observer pattern - when storing a Person
in a map, register a listener in that Person
. When e.g. age
changes, the listener notifies a tree (or another observer) storing people by age and handles removal and adding back.
BTW if you try to remove an object after it was modifed, you will fail - TreeMap
will no longer be able to find an object to be removed...
Upvotes: 2