How you write collections (arrayList, vector, etc) as attribute in UML (Class Diagram)?

Viewed 3545

I want to ask how I write collections (arrayList, vector) as attribute inside class diagram?

Because when you want to add variable as an attribute you can write it like "+ name: string", but how does it work with vector? Thanks.

3 Answers

See this tutorial on “multiplicity” and “multiplicity element” in a UML diagram.

Cardinality

Follow the attribute name and type with an interval of one or two numbers in square brackets joined by 2 dots.

For exactly one:

goalKeeper : Player [1..1]

…or:

goalKeeper : Player [1]

For multiples, two to three:

forwards : Player [2..3]

Use asterisk for open-ended.

  • Zero or more: [0..*]
  • One or more: [1..*]

Must be zero: [0..0] or [0]

Collection properties

Follow the multiplicity-range with characteristics of:

  • ordered or unordered (meaning sorted)
  • unique or nonunique (meaning distinct)

Nest those values in curly braces, separated by comma.

Java

You said:

I write collections (arrayList, vector)

By the way, never use Vector. That legacy class was supplanted many years ago by ArrayList, as noted in the Javadoc.

Let's look at how the Java Collections Framework fits these properties.

A Java Set would be { unordered, unique }. A Java SortedSet or NavigableSet would be { ordered, unique }. A Java List would be { ordered , nonunique }. As to the last combination { unordered , nonunique }, no such interface nor implementation is bundled with Java; see the 3rd-party solution, Multiset in Guava.

Table showing a Java collection class for each combination of ordered/unordered with unique/nonunique UML multiplicity property.

Example

Back to your example of some entity having names, say one or more names listed in order of preference:

+ names: string [1..*] { ordered , unique }

Your attribute name should likely be plural, such as names here rather than singular name.

The answer by Basil Bourque is correct and to the point. This answer is just an addition to his answer.

When you want to depict a name, all you think of is that a name is a string of characters and thus, you do not mention in the class diagram whether it is StringBuilder or StringBuffer or CharSequence etc. You simply mention String which does not mean String class.

Another example is birthDate for which you will simply mention Date; not LocalDate, ZonedDateTime, or OffsetDateTime etc. Here, Date does not mean the infamous java.util.Date class; it simply means a date type of object.

To summarize this, when you mention a collection, all you need to mention is the cardinality, not the exact implementation class (like List, Set, Vector etc.) e.g.

history: History[0..*]

means the attribute, history is of type collection and the elements will of type, History.

in the same way you do for the other types, for instance + name: Vector<String> because the type can be specified as a free text

Related