Aggregate

From Wikibooks, open books for an open world
Jump to: navigation, search

Generics Java Programming
Aggregate
Collection
Navigate Collection topic: v  d  e )
Topics:

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 java.util.Collection and java.util.Map . Implementations for those interfaces are not interchangeable.

Collection[edit]

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

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

Map[edit]

The implementations of java.util.Map 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[edit]

A collection is better when you have to access to all the items at once. A map is better when you have to randomly access to 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 null 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 Collection, or a Map.

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.


Generics Java Programming
Aggregate
Collection