Lesson 9 | Indexed properties |
Objective | Learn about indexed properties. |
Bean Indexed Properties
JavaBeans also supports
indexed properties[1], which are properties that are very similar to normal Java arrays. Indexed properties contain several elements of the same type that can be accessed through a single integer index; hence the name indexed property. In this way, indexed properties work very much like normal Java arrays.
Indexed Properties
So far we have been talking about properties that have only one value. For each named property, we have a single associated value.
But this is not always the best way to represent properties; sometimes a property is better modeled as having multiple values. You can create properties that are actually an ordered collection of values associated with a single name. The individual values are accessed using an integer index, much the same way you would with an array.
There is an additional design pattern for indexed properties.
The <PropertyType> in the standard property method design pattern may be an array, as follows:
public <PropertyType>[] get<PropertyName>();
public void set<PropertyName>(<PropertyType>[] value);
These methods are used to access the entire array of property values at one time.
An additional method can be used to provide access to individual values in the property array. The method signatures for this pattern are:
public <PropertyType> get<PropertyName>(int index);
public void set<PropertyName>(int index, <PropertyType> value);
Single Value Pattern
As with the single value pattern, these methods are allowed to include a throws clause for throwing checked exceptions. Specifically, the indexed methods may throw a java.lang.ArrayIndexOutOfBoundsException if an index is used that is outside the bounds of the property array. Although this is an important aspect of indexed properties, it isn't required for the indexed properties pattern. Since the indexed properties are considered ordered collections, I think the indexed get()
and set() methods should always declare the ArrayIndexOutOfBoundsException. It might have been better to make it a requirement for this pattern.
In the next lesson, indexed property accessor methods will be discussed.
[1] Indexed properties: a property representing an array of values.