Home > Articles > Software Development & Management > UML

  • Print
  • + Share This
This chapter is from the book 20.5 Collection Classes in Code

20.5 Collection Classes in Code

One-to-many relationships are common. For example, a Sale must maintain visibility to a group of many SalesLineItem instances, as shown in Figure 20.5. In OO programming languages, these relationships are usually implemented with the introduction of a collection object, such as a List or Map, or even a simple array.

Figure 20.5 Adding a collection.

For example, the Java libraries contain collection classes such as ArrayList and HashMap, which implement the List and Map interfaces, respectively. Using ArrayList, the Sale class can define an attribute that maintains an ordered list of SalesLineItem instances.

The choice of collection class is of course influenced by the requirements; key-based lookup requires the use of a Map, a growing ordered list requires a List, and so on.

As a small point, note that the lineItems attribute is declared in terms of its interface.

Guideline: If an object implements an interface, declare the variable in terms of the interface, not the concrete class.

For example, in Figure 20.5 the definition for the lineItems attribute demonstrates this guideline:

private List lineItems = new ArrayList();
  • + Share This
  • 🔖 Save To Your Account