Java data structure issue

I was wondering what would be the best data structure to use in the following scenario:

I have 2 types of objects A and B

A may contain many instances of B

The name A. is unique. B.name is unique inside instance A (although not unique globally)

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

All help is much appreciated

Chris

+5
source share
4 answers
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;
    }
}
+1
source

It sounds like you need something like this (with the exception of 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);
    }
}
+6
source

A :

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

- B B :

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

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

, B.

You can extend the same logic to support a map onto which A's unique names are entered:

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 aMapinside another class and implement the method getB:

public B getB(String aName, String bName) {
   return aMap.get(aName).getB(bName);
}
0
source
class a {
    String name
    List<B> bList

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


}
0
source

All Articles