Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java data structure question

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

like image 945
QuakerOat Avatar asked Jul 29 '10 22:07

QuakerOat


People also ask

What is data structure in Java with example?

What are Data Structures in Java? Data Structure in java is defined as the collection of data pieces that offers an effective means of storing and organising data in a computer. Linked List, Stack, Queue, and arrays are a few examples of java data structures.

What are the data structures in Java?

Examples of linear data structures are array, stack, queue, linked list, etc. Static data structure: Static data structure has a fixed memory size. It is easier to access the elements in a static data structure. An example of this data structure is an array.


2 Answers

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);
    }
}
like image 157
Jon Skeet Avatar answered Sep 24 '22 18:09

Jon Skeet


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;
    }
}
like image 39
Kylar Avatar answered Sep 22 '22 18:09

Kylar