From Indices to Keys
• We can define an adapter class that defines an indexer:
139
© Dr Markus Lumpe, 2021
Indexer Constructor
Arrays are passed as pointers to the first element to functions in C++.
We must use member initializer to initialize const instance variables!
140
© Dr Markus Lumpe, 2021
The Indexer
• We use the const specifier to indicate that the operator[]: • is a read-only getter
• does not alter the elements of the underlying collection
• We use a const reference to avoid copying the original value stored in the
underlying collection.
141
© Dr Markus Lumpe, 2021
stoi
Testing the Indexer
142
© Dr Markus Lumpe, 2021
How can we define an indexer in Java?
143
© Dr Markus Lumpe, 2021
The Transition to Java
• We need to define an Indexer class.
• Java does not support operator overloading. So, we need to map [] to a member function.
• The built-in type Integer provides the required conversion operations.
• We use IndexOutOfBoundsException to signal an index error.
144
© Dr Markus Lumpe, 2021
Indexer’s at( String aKey ) Method
145
© Dr Markus Lumpe, 2021
The Indexer’s main Method
146
© Dr Markus Lumpe, 2021