Name

ArrayList<E>

Synopsis

This class is a List implementation based on an array (that is recreated as necessary as the list grows or shrinks). ArrayList implements all optional List and Collection methods and allows list elements of any type (including null). Because ArrayList is based on an array, the get( ) and set( ) methods are very efficient. (This is not the case for the LinkedList implementation, for example.) ArrayList is a general-purpose implementation of List and is quite commonly used. ArrayList is very much like the Vector class, except that its methods are not synchronized. If you are using an ArrayList in a multithreaded environment, you should explicitly synchronize any modifications to the list, or wrap the list with Collections.synchronizedList( ). See List and Collection for details on the methods of ArrayList. See also LinkedList.

An ArrayList has a capacity, which is the number of elements in the internal array that contains the elements of the list. When the number of elements exceeds the capacity, a new array, with a larger capacity, must be created. In addition to the List and Collection methods, ArrayList defines a couple of methods that help you manage this capacity. If you know in advance how many elements an ArrayList will contain, you can call ensureCapacity( ), which can increase efficiency by avoiding incremental reallocation of the internal array. You can also pass an initial capacity value to the ArrayList( ) constructor. Finally, if an ArrayList ...

Get Java in a Nutshell, 5th 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.