More specific about the question: //There're two classes A and B:
Class A {
public static List<B> b = new ArrayList<B>();
}
Class B {
}
In my schema, I want to an object b from Class B. Then under all circumstances,object b will involve at least two objects "a_x" and "a_y" from Class A. How can I create such a relationship?
First thing,This public static List<B> b = new List<B>();
wont compile.
You might need public static List<B> b = new ArrayList<B>();
You cannot instantiate an Interface.So provide an concreate implementation. Ex:ArrayList
And second thing,You should add them directly where ever your are creating this list
.
If you have a relation where each B
is related to at least two A
instances, then B
needs a collection-typed field. For example:
public class B {
private List<A> relatedAList = new ArrayList<>();
...
}
This needs to be an instance field, not a static field.
But if you have a 2+
relationship, it doesn't make sense to call the related objects x
and y
... because what if there is a z
, and a p
and so on. Unless there is a fixed upper bound on the number of related A
objects for each B
, you have to use some kind of collection to represent each B
's related A
s.
This is the relationship:
class A
{
public List<B> b = new ArrayList<B>();
}
class B
{
A ax;
A ay;
B(A ax, A ay)
{
this.ax = ax;
this.ay = ay;
}
}
This is what you need?
Why do you need such relantioship?
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.