Java many to many association map
Posted
by Raphael Jolivet
on Stack Overflow
See other posts from Stack Overflow
or by Raphael Jolivet
Published on 2010-04-03T15:24:23Z
Indexed on
2010/04/03
15:33 UTC
Read the original article
Hit count: 315
Hi,
I have to classes, ClassA and ClassB and a "many to many" AssociationClass. I want to use a structure to hold the associations between A and B such as I can know, for each instance of A or B, which are their counterparts.
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.
Thanks in advance for your help,
Raphael
NB: This is not a "database" question. These objects are pure POJO used for live computation, I don't need persistence stuff.
© Stack Overflow or respective owner