Array Index Out of Bounds

In this lesson, we will look at the error we get when an index gets too large.

Completing the toArray method

Let’s complete the definition of the method toArray so that it is no longer a stub.

Because the array bag is a private data field in the class BagOfStrings, toArray should return a reference to a copy of bag instead of returning a reference to bag itself. Doing so will prevent the client from damaging the bag’s contents. So, after allocating a new array of strings to hold the current contents of the bag, toArray should copy the references in the array bag to this new array and return the result to the client:

/** Retrieves all strings that are in this bag.
    @return a newly allocated array of all the strings in this bag. */
public String[] toArray()
{
   String[] result = new String[numberOfStrings];

   // Copy numberOfStrings entries from bag to result:
   for (int index = 1; index <= numberOfStrings; index++)
      result[index] = bag[index];

   return result;
} // End toArray

Get hands-on with 1200+ tech skills courses.