Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I store a value based on two objects in Java?

Tags:

java

I have some objects, lets just call them Person objects. I also have some other objects, lets call them Relationship objects.

I want to be able to assign a Relationship object between two Person objects, but I'm not really sure what a good way to go about this is.

I was thinking of maybe giving each Person object an ID and then creating a 2D array of Relationship objects using the Person object ID as the key values.

I'm not sure if that's the best approach though as the array would have a lot of null values wherever there isn't a relationship between two Person objects.

like image 428
user11406 Avatar asked Feb 06 '26 21:02

user11406


1 Answers

@Makoto's a good idea. Alternatively, what sounds to me a litte bit more natural is to have Relationship object hold two Person objects passed e.g. as constructor arguments. You'll then need to track only the Relationship objects because they'll have knowledge about both Persons that are the parts of it.

class Relationship {
Person firstPerson;
Person secondPerson;

  public Relationship(Person firstPerson, Person secondPerson) {
    this.firstPerson = firstPerson;
    this.secondPerson = secondPerson;
}

Alternatively you can use a public method to pass the reference to the Person objects if you don't want them to be passed via constructor:

public void setPersons(Person firstPerson, Person secondPerson) {
  this.firstPerson = firstPerson;
  this.secondPerson = secondPerson;
}
like image 110
ttarczynski Avatar answered Feb 09 '26 10:02

ttarczynski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!