Reputation: 3548
I hope this won't sound like a stupid question.
I have a class A and a class B. Now the only thing B has is a String ID. Now I can have multiple objects A that each can have 0 or more objects of type B. These are contained in a HashMap(ID,someData) each class A has.
What I want to do is each time I add a new ID in class A to check whether there already is a on object of Type B with the same ID in any of the other class A objects I have, and if not, create a new B object.
Hope this makes sense. If what I ask is wrong is some way, please be kind enough to explain how is this a bad practice or conceptualy wrong.
Thanks a lot.
EDIT:To be more clear,in my case, it is not desireable to share the HashMap(ID,someData) for all my objects as for example let's say A is a Course class,Or Catalogue, or Bank etc. Each A class may share some students/clients but each A class may contain different class B objects.
Upvotes: 4
Views: 168
Reputation: 1086
You should loop through all your A instances and use Hashmaps containsKey method to check that the new B value is already stored or not. If you only need to store all the B values to every A class only once, you can add a static modifier for your HashMap field.
Upvotes: 0
Reputation: 104168
If I were you I would have created a B_Factory class. This class would be responsible for creating the B objects. A class objects would call B_Factory methods to add or delete a B object. Inside B_Factory, you could use a Map to store the instances of B objects.
There should be only one instance of B_Factory class, which will be injected in all A instances.
Upvotes: 0
Reputation: 2154
To achieve your purpose, you can make the HashMap a static
variable, instead of an instance variable. Therefore, it will be shared among all instance of Class A.
Upvotes: 0
Reputation: 533482
The thing you need to do this is to have a collection of all A objects so you can check them all. As you get more A objects this will become more inefficient. A diiferent was to structure this might be to use the ID as you collection.
Map<ID,/* class with A and someData *> map = ...
This allows you to ensure uniqueness of ID across all A.
Upvotes: 0
Reputation: 258558
It's not bad practice, it seems like you're implementing the Instance Manager Pattern.
- Ability to look up one or more instances (via a key) of the managed object(s). If only one managed object, then a key is not necessary.
Upvotes: 4