Java many to many association map

前端 未结 7 1058
难免孤独
难免孤独 2020-12-16 01:29

I have two classes, ClassA and ClassB, as well as a \"many to many\" AssociationClass. I want a structure that holds the associations

7条回答
  •  醉酒成梦
    2020-12-16 01:52

    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:

    public class Data {
    
      public ClassA a;
      public ClassB b;
      public AssociationClass association;
    
    }
    
    Map aData;
    Map bData;
    Map associationData;
    

    Inserting goes like this:

    Data data = new Data()
    
    aData.put(data.a, data);
    bData.put(data.b, data);
    associationData.put(data.association, data);
    

    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:

    Map, Data> pairData;
    

    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.

提交回复
热议问题