Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Object reference or identifier?

Tags:

java

I am currently creating a big project, and as such I would like to have everything worked out very well and as efficient as possible.

In my project, I have a class called Teams, which contains a HashMap(Integer, Team) of Team objects. Each instance of Team has a unique ID (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 what Team a Player is assigned to:

-> Store the ID of the team in Player (private int team), this ID is then used to get the Team from the HashMap in Teams.

-> Store a reference to the Team in Player (private Team team)

Does anyone know which is better, and what the most important pro's, con's and dangers are of each?

Thanks!

like image 239
Insdeath Avatar asked Sep 29 '11 11:09

Insdeath


1 Answers

Use private Team team! Other classes should not need to know the ID of an object unless there is a good reason. Don't implement a Database structure in Java. Java is designed to be Object-based, use it that way.

There are a couple additional reasons you should hold the Team instance:

  1. We can assume that your Player will need to access the Team object. It is better to have the instance rather than having to do a lookup.
  2. If you hold onto IDs instead of instances, there might not be any reference to an object being held and it could be garbage collected. I know that probably won't happen in your case since you hold all Teams in a Map, but it is still a risk and therefore should be avoided.
like image 105
John B Avatar answered Oct 19 '22 23:10

John B