Use indexOf only when you must maintain an existing expression. It returns the position of an object in a sequence, but its zero-based result does not match the one-based indexing used by at.
Signature
indexOf(object : T) : Integer
indexOf searches the sequence in self for object and returns its position.
Return value
| Result | Meaning |
|---|---|
0 or greater
|
The zero-based position of the object in the sequence. 0 is the first element.
|
-1
|
The object is not present in the sequence. |
For example, if a sequence contains the cars Toyota and Volvo, in that order, finding Toyota with indexOf returns 0. Finding a car that is not in the sequence returns -1.
Important: index base does not match at
indexOf is zero-based, while at is one-based. Do not pass an indexOf result directly to at.
For example, when indexOf(Toyota) returns 0, that value identifies the first item under zero-based indexing. The at operator uses one-based indexing, where the first item is position 1. This difference can produce an off-by-one result.
Use the explicit zero-based operators
For new OCL expressions, use indexOf0 together with at0. Both operators use zero-based indexing, so their results and input values align.
- Find the position with
indexOf0. - Check whether the result is
-1before using it as an index. - Retrieve an item with
at0when you need to use that position.
Example: if indexOf0(Toyota) returns 0, at0(0) refers to the first item in the sequence.
Handle objects that are not found
A result of -1 means that the search did not find the object. Do not use -1 as an index. Test the result first when the object may be absent.
Use isEmpty when you need to test whether a collection contains any elements before performing collection work.
