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
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.
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.
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);
}
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With