Java Classes and Constructors

Hope this doesn't seem like a silly question.

I have class A and class B. Now the only thing that has B is String ID. Now I can have several objects A, each of which can have 0 or more objects of type B. They are contained in the HashMap (ID, someData), which each class A has.

What I want to do is every time I add a new identifier to class A to check if there is already an on object of type B with the same identifier in any of the other objects of class A that I have, and if no, create a new object B.

Hope this makes sense. If what I ask is wrong anyway, please be kind enough to explain how this is bad practice or conceptually wrong.

Many thanks.

EDIT: to be more clear, in my case it is not advisable to share a HashMap (ID, someData) for all my objects, for example, let them say that A is a course class, or a directory or a bank, etc. Each Class can be shared by some students / clients, but each Class A can contain different objects of class B.

+4
source share
5 answers

Good practice, it looks like you are implementing an instance template .

  • The ability to search for one or more instances (via the key) of the managed object (s). If there is only one managed entity, then the key is not needed.
+4
source

What you need to do is collect all objects A so that you can check them. When you get more A objects, it will become more inefficient. It was diverse to structure this; perhaps it would be to use an identifier as a collection.

Map<ID,/* class with A and someData *> map = ... 

This allows you to guarantee the uniqueness of ID for all A.

0
source

To achieve your goal, you can make the HashMap variable a static instead of the instance variable. Therefore, it will be used for all instances of class A.

0
source

If I were you, I would create a B_Factory class. This class will be responsible for creating the B objects. The class objects will call the B_Factory methods to add or remove the B object. Inside B_Factory you can use a map to store instances of the B objects.

There must be only one instance of the B_Factory class, which will be introduced in all instances of A.

0
source

You should skip all instances of A and use the Hashmaps containsKey method to verify that the new value of B is already stored or not. If you only need to save all B values ​​for each class A only once, you can add a static modifier for your HashMap field.

0
source

Source: https://habr.com/ru/post/1399747/


All Articles