Gambit
Gambit

Reputation: 11

A data structure for many-to-many symmetric relationship (person friends problem)

I'm kinda of a newbie. I have a question regarding which Java collection (no Hibernate, databases, etc.) is best to use to implement many-to-many symmetric relationship. HashMap with values V=sets of keys? But then delete, add operations become very slow... Any suggestions?

Thanks.

Upvotes: 1

Views: 766

Answers (1)

jjnguy
jjnguy

Reputation: 138864

One way you could do it is use two Maps. One Map<Object1, Object2>, and one Map<Object2, Object1>.

You could add each pair of related objects to both maps. That way you can look up the relationships both ways really quickly. You will also need to remove pairs from both maps when a relationship is removed.

Removal of the relationships becomes a little slow, but adding and finding is constant time.

Upvotes: 2

Related Questions