简体   繁体   English

如何将两个不同的对象相互关联

[英]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:从你的描述看来你需要公民对象中的列表,你可以提供addDose(Dose dose) function,你甚至可以添加 setter function setDoses(List<Dose> doseList)一步设置列表 Dose,例如喜欢:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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