英文:
Link 2 objects and get them from each
问题
我最近遇到了这个问题,我想找到最合适的解决方案。
我有两个对象,A和B,B可以包含多个A,并且我希望它们能够彼此获取,即:A.getB(); 和 B.getAs();
在这种情况下,最好的方法是什么?我曾考虑过这样做:
for (A a : aList) {
a.getB().addA(a);
}
因此,调用 a.getB().getAs().contains(a);
将会返回 true。
提前感谢您的帮助。
英文:
I recently ran into this problem and I want to see the most suitable solution.
I have 2 objects, A and B, B can contain multiple A's, and I want it to be able to get them from each other, i.e: A.getB(); and B.getAs();
What would be the best way to do this? I had thought of doing something like this:
for (A a : aList) {
a.getB().addA(a);
}
Therefore, calling a.getB().getAs().contains(a); would return true
Thanks in advance.
答案1
得分: 1
几乎与tashkhisi的回答相同,但我认为他漏掉了 a.setB(this);
... 无论如何,代码如下。我还在A类的setB方法中添加了帮助程序,但最好还是只通过关系的“拥有”一侧添加。
假设:任何单个A只能属于一个B,否则需要在两侧都需要列表,并使用不同的帮助函数。
public class A {
private B b;
public B getB() {
return b;
}
public void setB(B b) {
this.b = b;
// 仅在您希望从任一端添加时才需要。
if (!(b.getAList()).contains(this)) {
b.getAList().add(this);
}
}
}
public class B {
private final List<A> aList = new ArrayList<>();
public List<A> getAList() {
return aList;
}
public void addA(A a) {
aList.add(a);
a.setB(this);
}
}
英文:
Almost the same as tashkhisi's answer but I think he missed a.setB(this);
... anyway code below. I also added helper on the setB method of the A class but it's probably better only to add through the 'owning' side of the relationship.
Assumption: any single A can only belong to one B, otherwise, it needs lists on both sides and different helper functions
public class A {
private B b;
public B getB() {
return b;
}
public void setB(B b) {
this.b = b;
// Needed only if you want to add from either end.
if (!(b.getAList()).contains(this)) {
b.getAList().add(this);
}
}
}
public class B {
private final List<A> aList = new ArrayList<>();
public List<A> getAList() {
return aList;
}
public void addA(A a) {
aList.add(a);
a.setB(this);
}
}
</details>
# 答案2
**得分**: 0
你正在正确的轨道上。在 A 上有一个 List<B>,在 B 上有一个 List<A>。编写适当的 getter 和 setter,并且在创建对象时不要忘记将它们插入到相应的列表中。
<details>
<summary>英文:</summary>
You're on the right track. Have a List<B> on A, and a List<A> on B. Code the appropriate getters and setters, and don't forget to insert your objects in the corresponding list when you create them.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论