The Methods getIndexOf and contains
Explore how to implement the private method getIndexOf to find the index of a string within an array and revise the contains method to use getIndexOf for cleaner code. This lesson helps you understand efficient searching in array-based Java collections and improving method design by isolating common logic.
We'll cover the following...
Having just defined the private method removeEntry in the previous lesson, we now need to locate the string to remove from the bag so we can pass its index to removeEntry. That is, we must define the private method getIndexOf.
Locating the string to remove: The dilemma
We want the private method getIndexOf to search the array of bag entries for a given string and to return the string’s index if it is found. But the method contains already does the same search. Unfortunately, contains returns true or false; it does not return the index of the string it locates in the array. Thus, getIndexOf cannot simply call contains.
...📝 Design decision: Should the method
containsreturn the index of a located entry?Should we change the definition of
containsso that it returns an index instead of a Boolean value?No!
- As a public method,
containsshould not provide a client with such implementation details.- The client should not expect that a bag’s entries are in an array, since they are in no particular order.