简体   繁体   中英

How to do I associate two different objects with each other

        Citizen c1 = new Citizen();
        Dose d1 = new Dose();   
        Dose d2 = new Dose();

Now I want to assign these two doses to this specific citizen and put them in a single list. So these objects are all related to each other in the list and are a same set of information.

from your description it looks you need list within Citizen objects, and you can provide addDose(Dose dose) function, even more you can add setter function setDoses(List<Dose> doseList) to set the list Dose in one step, example would be like:

public class Citizen {
...
...
List<Dose> doseList = new ArrayList<Dose>();
.
.
public void addDose(Dose dose){
doseList.add(dose);
}

public void setDoseList(List<Dose> doses){
doseList= doses;
}


}

The commentators are dead right, but I feel the short hints are not sufficient as an answer. Basically I am understanding two things in the question:

  • You want to assign the doses to a specific citizen - that part was answered in the comments
  • you want to put them all in one single list - we do not know whether that list should be doses, citizens or even a mix.

It all matters how you define your classes so you can navigate back and forth:

public class Dose {
    private Citizen citizen;

    public void setCitizen(Citizen citizen) {
        this.citizen = citizen;
    }

    public Citizen getCitizen() {
        return citizen;
    }
}

public class Citizen {
    private List<Dose> doses;

    public Citizen() {
        doses = new ArrayList<>();
    }

    public void addDose(Dose dose) {
        if (!doses.contains(dose)) {
            doses.add(dose);
            dose.setCitizen(this);
        }
    }

    public List<Dose> getDoses() {
        return new ArrayList<Dose>(doses);
    }
}

public static void main(String[] args) {
    Citizen c1 = new Citizen();
    Dose d1 = new Dose();   
    Dose d2 = new Dose();
    c1.addDose(d1);
    c1.addDose(d2);

    // let's see what doeses a citizen has
    System.out.println(c1.getDoses());
    // let's see where dose 1 ended up
    System.out.println(d1.getCitizen());

    // let's put them all in one list - that requires a common base class, and we currently have just 'Object'.
    List<Object> dosesAndCitizens = new ArrayList<>();
    dosesAndCitizens.add(c1);
    dosesAndCitizens.add(d1);
    dosesAndCitizens.add(d2);

    System.out.println(dosesAndCitizens);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM