bluehallu
bluehallu

Reputation: 10285

Multiple data structures over the same objects

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:

  1. Retrieve them by their idNumber.
  2. Get a list of the Persons where age > X.
  3. Get a list of all the persons sorted alphabetically by name.

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.

  1. Is this the best way?
  2. Is it necessary to remove a person from the age TreeMap before editing the age to then put it back in?
  3. 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?

Upvotes: 2

Views: 1103

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

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 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

Related Questions