Java Programming/Aggregate

In the previous chapters, we have discovered the array. An array stores a group of primitive types. To group objects, or to reference a group of objects, we can use Java aggregate classes. There are two main interfaces, those are  and. Implementations for those interfaces are not interchangeable.

Collection
The implementations of  interface are used for grouping simple java objects.


 * Example: We can group together all patients in a Hospital to a "patient" collection.

Map
The implementations of  interface are used to represent mapping between "key" and "value" objects. A Map represents a group of "key" objects, where each "key" object is mapped to a "value" object.


 * Example: For each patient, there is one and only one main nurse assigned to. That association can be represented by a "patient-nurse" Map.

Choice
A collection is better when you have to access all the items at once. A map is better when you have to randomly access an item regularly.

Before selecting a particular collection implementation, ask the following question: Can my collection contain the same elements, i.e. are duplicates allowed?

Can my collection contain the element?

''Should the collection maintain the order of the elements? Is the order important in any way?''

''How do you want to access an element? By index, key or just with an iterator?''

Does the collection need to be synchronized?

From a performance perspective, which one needs to be faster, updates or reads?

From a usage perspective, which operation will be more frequent, updates or reads?

Once you know your needs, you can select an existing implementation. But first decide if you need a, or a.

Note that the above associations are explicit. The objects them-self do not have any knowledge/information about that they are part in an association. But creating explicit associations between simple java objects is the main idea about using the aggregate/collection classes.

Programmeren in Java/Collections