Reputation: 85
I had a static object (hive) that was created within an object called Garden and I was using methods from hive in many other objects.
Now i have the need for multipul hives that contain different data (arrays and such.) So ive put the different Hives within a HashMap.
I still need to run methods from the hives that are now within the HashMap in other objects and I need it to be running the method from the correct instance of hive.
How would I call methods from hive as an object that is within a HashMap in a different Object?
class Garden()
{
Map<String, Hive> HiveMap = new HashMap<String, Hive>();
Hive hiveA = new Hive();
map.put("A", hiveA);
Hive hiveB = new Hive();
map.put("B", hiveB)
}
class Hive()
{
ArrayList bees<Bee bee> = new ArrayList();
Bee bossBee = new Bee;
void importantHiveBusiness()
{
...
}
}
class Bee()
{
//Garden.hive.importantHiveBusiness();
}
Not actual code just to try and show what im trying to do clearer. Thanks for any help
Bee wants to run the method from the hive that it is in(the bee is in arrayList)
Upvotes: 0
Views: 109
Reputation: 726
map.get("A").importantHiveBusiness()
Unless I'm interpreting your question wrong, this should do it.
Edit: Ah, I see what you're getting at here.
You'll need to decide whether your applications will use multiple Gardens, or just one. If you only need one Garden, you should use a "singleton" design pattern. Example below:
public class Garden {
public static final Garden GARDEN = new Garden();
private HashMap<String, Hive> hiveMap = new HashMap<String, Hive>();
private Garden() {
// create garden here
}
public HashMap<String, Hive> getHiveMap() {
return this.hiveMap;
}
}
The private constructor is very important. This ensures that (as long as you don't make any Garden objects within the Garden class' code, only one Garden can ever exist. The "static" keyword makes GARDEN accessible from everywhere in your code.
Then you can simply do...
public class Bee() {
// inside some method...
Garden.GARDEN.getHiveMap().get("A").importantHiveBusiness();
}
Alternately, if you want multiple gardens, then you only need to instantiate (create) a Garden object, and myGarden.getHiveMap().get("A").importantHiveBusiness();
Edit2:
It might be useful for the Bee class to contain a reference to its hive. This would eliminate the need for a HiveMap.
public class Bee {
private final Hive hive;
public Bee(Hive hive) {
this.hive = hive;
}
public getHive() {
return this.hive;
}
}
Upvotes: 1
Reputation: 612
Instantiate an object of class Garden and use
obj.HiveMap.get(”A”).importantHiveBusiness()
Upvotes: 1
Reputation: 311863
Once you have your Hive
s in a map, and have meaningful keys (according to your business logic) to it, you can just access the Hive
objects with the get
method:
class Bee() {
Garden.HiveMap.get("A").importantHiveBusiness();
}
Upvotes: 0