Object reference or id?

I am currently creating a large project, and therefore I would like everything to work out very well and as efficiently as possible.

In my project, I have a class called "Teams" that contains HashMap (Integer, Team) Team objects. Each instance of the command has a unique identifier (integer).

There is also an object called Player. Each instance of Player can be assigned to a team (but not always).

Now, I wonder what the best approach would be to know for which team the player is assigned:

-> Save the command identifier in Player (private int command), this identifier is then used to get the command from the HashMap in the commands.

-> Store a link to a command in Player (private command team)

Does anyone know which is better and what are the most important interests, problems and dangers of each of them?

Thanks!

+7
source share
5 answers

Use team team private teams ! Other classes do not need to know the identifier of an object unless there is a good reason. Do not implement the database structure in Java. Java is designed for Object-based, uses it that way.

There are several additional reasons why you should have a Team instance:

  • We can assume that your player will need access to the Team object. It is better to have an instance rather than doing a search.
  • If you hold identifiers instead of instances, there may not be any reference to the object that will be held, and this could be garbage collection. I know that this probably will not happen in your case, since you keep all the teams on the map, but this is still a risk, and therefore should be avoided.
+6
source

Obviously, this is impossible to say for sure here, without knowing the context in which it will be used, but from the point of view of code design, the β€œnatural” waiting time is that the team contains players, so the team that will refer to game objects, not vice versa.

If you are starting to mess with identifiers and need to store a large number of different objects, it looks like you are using the database more, in which case look at something like HSQLDB if you don't want to exit Java.

0
source

The potential danger of using an object reference as a key in a HashMap (or any map) is that if it does not work correctly, it can become a memory leak.

The object will not be garbage collected if there are links to it. If it is used as a key on the map, this is considered a link to this object.

You can get around this using WeakReference .

In the situation described, you should probably use objects as keys, but be careful with the above conditions.

0
source

private Team team is a way to go between the two approaches you mentioned. If you store the identifier, what happens if the HashMap is updated? This creates unnecessary dependencies.

0
source

Do you use a database? If so, save the command identifier in the player, otherwise I suggest you keep the command link.

-one
source

All Articles