Creating, Adding, and Removing Elements from an ArrayList

suggest change

ArrayList is a resizable array: its size does not have to be declared in advance. It stores object references.

It extends AbstractList and implements List. An ArrayList can contain duplicates and keeps insertion order. It is not synchronized, so concurrent use needs external coordination. Index access is fast because the list is backed by an array. Inserting or removing in the middle is slower because later elements are shifted.

An ArrayList can be created as follows:

List<T> myArrayList = new ArrayList<>();

T (Generics) is the type stored in the ArrayList.

The element type must be a reference type. A primitive type is not allowed; use the corresponding wrapper class.

To add an element, use add():

myArrayList.add(element);

Or to insert an element at an index:

myArrayList.add(index, element); //index of the element should be an int (starting from 0)

To remove the first matching element, use remove(Object). On a List<Integer>, remove(1) calls remove(int) and deletes index 1, not the value 1.

myArrayList.remove(element);

Or to remove an item from a certain index:

myArrayList.remove(index); //index of the element should be an int (starting from 0)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents