4

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.

5 Answers 5

4

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.
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.