iLalox
iLalox

Reputation: 43

Link 2 objects and get them from each

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.

Upvotes: 2

Views: 63

Answers (2)

Kipperfer
Kipperfer

Reputation: 128

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

Upvotes: 1

JustAnotherDeveloper
JustAnotherDeveloper

Reputation: 2266

You're on the right track. Have a List on A, and a List on B. Code the appropriate getters and setters, and don't forget to insert your objects in the corresponding list when you create them.

Upvotes: 0

Related Questions