views:

510

answers:

2

I seem to be using the wrong search terms for this in Google...

I have written a Generic Class for Many-To-Many Associations, but I'm guessing this has already been done. It is highly likely that it exists in an implementation much better than my own. This is my first foray into writing a generic class.

For a better idea of what I'm looking for, I am including some snippets of my own:

I've backed it with 2 hashmaps:

private final Map<T, List<S>> ssForTs = new HashMap<T, List<S>>();
private final Map<S, List<T>> tsForSs = new HashMap<S, List<T>>();

Here is the instantiation:

new ManyToManyAssociations<Integer, Integer>();

Some of the methods available:

  • public void addAssociation(T t, S s)
  • public void removeAssociation(T t, S s)
  • public List<T> getListOfTs()
  • public List<S> getListOfSs()
  • public List<T> getTsForSs(S s)
  • public List<S> getSsForTs(T t)

The names of the methods are quite poor... I apologize.

Basic usage is: I can find all S for T and the reverse quite easily.

Can you post the link to a polished library that already includes this functionality?

+1  A: 

Looks like Apache Commons Multimap might be useful.

EDIT: except it's one-to-many, not many-to-many. However, it still might be handy to use instead of your Map<T, List<S>> and Map<S, List<T>>, or as a reference.

Michael Myers
+2  A: 

So far, this is a less trivial question than I thought. The two Java Collections extensions I know of off the top of my head are the Google one mentioned by duffymo, and the Apache Commons Collections. Neither has a many-to-many map. In Google's terminology, it would be a BiMultiMap; in Apache's, it would be a BidiMultiMap or MultiBidiMap.

Paul Brinkley