Demonstrating an ArrayList<String>

Figure 7.24 demonstrates some common ArrayList capabilities. Line 10 creates a new empty ArrayList of Strings with a default initial capacity of 10 elements. The capacity indicates how many items the ArrayList can hold without growing. ArrayList is implemented using a conventional array behind the scenes. When the ArrayList grows, it must create a larger internal array and copy each element to the new array. This is a time-consuming operation. It would be inefficient for the ArrayList to grow each time an element is added. Instead, it grows only when an element is added and the number of elements is equal to the capacity—i.e., there’s no space for the new element.

 1   // Fig. ...

Get Java™ How To Program (Early Objects), Tenth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.