george
george

Reputation: 57

Associate one and only one object

Hello I have one question.

I have Class A and Class B. I create one object A and multiple objects B. But I want only one B can set with A. e.x

class A{} 
class B{ private A a;}
public static void main(String[] args){
     A a= new A();
     B b= new B();
     B c= new B();
     b.setA(a);
     c.setA(a);//Sould not assign it.
}

Upvotes: 0

Views: 116

Answers (1)

Anuj
Anuj

Reputation: 1665

Here is one way to implement such a concept.


Code

class A {}

public class B
{
    private static final HashSet<A> setA = new HashSet<>();
    private A a;

    public void setA(A a)
    {
        if (!setA.contains(a))
        {
            this.a = a;
            setA.add(a);
        }
    }

    public A getA() { return a; }

    public static void main(String[] args)
    {
        A a0 = new A();
        A a1 = new A();

        B b0 = new B();
        B b1 = new B();
        B b2 = new B();

        b0.setA(a0);
        b1.setA(a1);
        // Below two operations fail silently
        b2.setA(a0);
        b2.setA(a1);

        System.out.println(b0.getA());
        System.out.println(b1.getA());
        System.out.println(b2.getA());
    }
}

You can even throw a custom exception instead of failing silently.


Output

george_17092021_1434.A@568db2f2
george_17092021_1434.A@378bf509
null

Conclusion

Doing so should help in achieving what you want. However, I do not know if this is something to be used professionally or not. Please comment if you face any problems.

Upvotes: 1

Related Questions