Java Language Lists Creating, Adding and Removing element from an ArrayList


ArrayList is one of the inbuilt data structures in Java. It is a dynamic array (where the size of the data structure not needed to be declared first) for storing elements (Objects).

It extends AbstractList class and implements List interface. An ArrayList can contain duplicate elements where it maintains insertion order. It should be noted that the class ArrayList is non-synchronized, so care should be taken when handling concurrency with ArrayList. ArrayList allows random access because array works at the index basis. Manipulation is slow in ArrayList because of shifting that often occurs when an element is removed from the array list.

An ArrayList can be created as follows:

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

Where T ( Generics ) is the type that will be stored inside ArrayList.

The type of the ArrayList can be any Object. The type can't be a primitive type (use their wrapper classes instead).

To add an element to the ArrayList, use add() method:


Or to add item to a certain index:

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

To remove an item from the ArrayList, use the remove() method:


Or to remove an item from a certain index:

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