简体   繁体   English

Java-在2个类之间创建“多对多”关系

[英]Java - Create a “many-to-many”-relation between 2 classes

I will try to explain my problem based on an example: 我将尝试基于一个示例来解释我的问题:

We have one class called " Car ", and one called " Worker ". 我们有一类叫“ 汽车 ”,另一类叫“ 工人 ”。

One car gets build by multiple workers, while one worker has built multiple cars. 一辆汽车由多名工人建造,而一名工人建造了多辆汽车。

My question is: 我的问题是:

How do I create some kind of "many-to-many"-relationship between those two classes, like commonly used with databases, WITHOUT importing any library except for the java.lang.* and java.io.* packages, which means that "List" is thereby excluded, because it is in java.util.* 我如何在这两个类之间创建某种“多对多”关系,例如通常与数据库一起使用,而不导入除java.lang。*和java.io. *包以外的任何库,这意味着因此,“列表”被排除在外,因为它在java.util。*中。

Thanks in advance :) 提前致谢 :)


Edit for further explaination: 编辑以进一步解释:

In databbases, you normally have a third table to split this "mtm"-relationship, so I thought at something like this on my picture. 在数据库中,通常会有第三个表来拆分此“ mtm”关系,因此我想到了这张照片上的类似内容。 在此处输入图片说明 Would this be possible? 这可能吗?

Obviously, in this case lists would be the best choice, but if you cannot use them, you could use arrays, something like this: 显然,在这种情况下,列表是最佳选择,但是如果您不能使用它们,则可以使用数组,如下所示:

class Car {  
   private Worker[] builtBy;
   ...  
}

class Worker {  
   private Car[] carsBuilt;
   ...  
}

However, the main disadvantage is that arrays are fixed-size so if you need to add more elements to the array than the initially allocated amount, you would have to create a new one and copy the contents there. 但是,主要缺点是数组是固定大小的,因此,如果您需要向数组中添加的元素数量超过最初分配的数量,则必须创建一个新元素并将其内容复制到该数组中。

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

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