I have two classes, ClassA
and ClassB
, as well as a "many to many" AssociationClass
. I want a structure that holds the associations between A and B so that I can find the counterpart for each instance of A or B.
I thought of using a Hashmap, with pair keys:
Hasmap<Pair<ClassA, ClassB>, AssociationClass> associations;
This way, I can add and remove an association between two instances of ClassA
and ClassB
, and I can query a relation for two given instances.
However, I miss the feature of getting all associations defined for a given instance of ClassA
or ClassB
.
I could do it by brute force and loop over all keys of the map to search for associations between a given instance, but this is inefficient and not elegant.
Do you know of any data structure / free library that enables this? I don't want to reinvent the wheel.
NB: This is not a "database" question. These objects are pure POJO used for live computation, I don't need persistence stuff.
Maybe the Multimap or the BiMap from the Google Collections Library can do what you need.
Using your AssociationClass, you could just have ClassA and ClassB both contain a reference to AssociationClass:
Or, a different method...
ClassA can contain:
and ClassB can contain:
By implementing this, you can access your associations from within the associated class.
Why not put a map in each class?
Here's my implementation based on guava Multimap:
Thanks for your suggestions.
I finally reinvented the wheel ... I have written a generic class for holding associations. I use two maps of maps, synchronized.
The associations holder provides the following methods
Here is the code:
I hope this can help someone in the future.
This looks like a problem in which you have data that you want to get using multiple keys. You want to search by ClassA and also by ClassB. This usually leads to multiple maps atop the data so that each map keeps a search key into the underlying data. Perhaps something like this would work:
Inserting goes like this:
Getting the data you can query each of the maps to get what you want. You can even have your
Pair
class as another index into the data:The problem with this approach is that if the underlying data changes a lot you must make sure that all maps are in sync. If this is mostly a readonly problem then you create the maps and then just query the one with your key into the data.