Is ArrayList<X> an aggregation or composition?

▼魔方 西西 提交于 2021-02-05 08:33:06

问题


I am preparing for my programming exam and came across this question, I know that in aggregation the object is borrowed, and in composition the object is owned. Is the answer composition?

Is an ArrayList<X> an aggregation of X or composition of X?

ArrayList<Point> pts = new ArrayList<Point>();
Point p = new Point(0., 0., 0.);
pts.add(p);
p.setX( 10.0 );
System.out.println(p);
System.out.println(pts.get(0));

回答1:


From here:

Simple rules:

  1. A "owns" B = Composition : B has no meaning or purpose in the system without A
  2. A "uses" B = Aggregation : B exists independently (conceptually) from A

Therefore, it really depends on your model. Can the elements in the list, exist without the list. Does the elements have to be put into the list to be meaningful?

In the case of ArrayList<Point>, I think it is an aggregation.




回答2:


Since Point has a real existence outside of the array, it's an aggregation.

https://www.visual-paradigm.com/guide/uml-unified-modeling-language/uml-aggregation-vs-composition/

as stated:

Aggregation implies a relationship where the child can exist independently of the parent. Example: Class (parent) and Student (child). Delete the Class and the Students still exist.

Composition implies a relationship where the child cannot exist independent of the parent. Example: House (parent) and Room (child). Rooms don't exist separate to a House.



来源:https://stackoverflow.com/questions/54988783/is-arraylistx-an-aggregation-or-composition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!