views:

110

answers:

4

Hi,

I was wondering what would be the best data structure(s) to use for the following scenario:

I have 2 object types A and B

A may contain many instances of B

A.name is unique. B.name is unique within it's instance of A (though not globally unique)

I would like to be able to provide accessor methods such as getA(String aName) returns a; getB(String aName, bName) returns b;

All help is much appreciated,

Chris

A: 

If A maintained an internal map like so:

Map<String, B> bMap = new LinkedHashMap<String, B>();

And you had a member functions to insert instances of B and get instances of B and like so:

public void addB(B b) {
    bMap.put(b.getName(), b);
}

public B getB(String name) {
    return bMap.get(name);
}

Then you can be sure that the map will contain keys with unique B names.

You can extend this same logic to maintain a map that is keyed by unique A names:

A a = new A("someAName");
a.addB(new B("someName"));
a.addB(new B("someOtherName"));

Map<String, A> aMap = new LinkedHashMap<String, A>();
aMap.put(a.getName(), a);

You can put aMap inside another class and implement a getB method:

public B getB(String aName, String bName) {
   return aMap.get(aName).getB(bName);
}
Vivin Paliath
+6  A: 

It sounds like you need something like this (except with better names, initialization, error handling etc - this is just a skeleton):

public class AContainer
{
    private Map<String, A> map;

    public A getA(String name)
    {
        return map.get(name);
    }

    public B getB(String nameA, String nameB)
    {
        return getA(nameA).getB(nameB);
    }
}

public class A
{
    private Map<String, B> map;

    public B getB(String name)
    {
        return map.get(name);
    }
}
Jon Skeet
A: 
class a {
    String name
    List<B> bList

    public getName() {....}
    public getBByName(String name) {
    ....
    }


}
hvgotcodes
+1  A: 
public class DataStructure{
      private Map<String, A> aMap = new HashMap<String, A>();
      public getA(String name){
          return aMap.get(name);
      }
      public getB(String aName, String bName){
          A anA = getA(aName);
          if(null != anA){
              return anA.getB(bName);
          }else{ 
              return null;
          }
    }
}
public class A{
    String name;
    Map<String, B> myBs = new HashMap<String, B>();
    public A(String name){
        this.name = name;
    }
    public void putB(B foo){
        myBs.put(foo.getName(), foo);
    }
    public B getB(String bName){
        return myBs.get(bName);
    }

 }


public class B{
    String name;
    public B(String name){
        this.name=name;
    }
}
Kylar
Thanks guys for all your replies - this has been really helpful!!The people here at stackoverflow rule :)
QuakerOat