prev table of contents next

2.2.12.5 Content: A Homogeneous List of Elements

To define an element where some sub-element occurs repeatedly, we make use of the optional attributes minOccurs and maxOccurs. Various combinations are possible, permitting the definition of a list that may be empty, may contain any number of elements, or a fixed number. The definition of an unbounded list with at least two elements is given below. (PointType is shown in subsection Content: An Ordered Set of Elements.)

<xsd:complexType name="PolygonType">
  <xsd:sequence>
    <xsd:element name="Points" type="PointType"
                 minOccurs="2" maxOccurs="unbounded"/>
  </xsd:sequence>
</xsd:complexType>
The resulting Java code does not express the required minimum of two points in a polygon. Here, and for all similar element lists, a java.util.List is used. Therefore the generated code will always be as simple as the one shown below.
public class PolygonType {
 
    protected List<PointType> points;
 
    public List<PointType> getPoints() {
        if (points == null) {
            points = new ArrayList<PointType>();
        }
        return this.points;
    } 
}
The Javadoc documentation (omitted here) emphasizes that getPoints returns a reference to the actual list while making sure that the list is created. All methods defined in java.util.List may be applied to the returned value.Most importantly, code like this
polygon.getPoints().add( new PointType( 4, 9 ) );
adds another point. The list can be added to one by one, or you may use addAll for bulk additions, and you could remove or even clear to delete elements. With all of these possibilities there is just no need for a setter for the entire list.


prev table of contents next