In Java, an ArrayList is a part of the Collection Framework. It is used to store dynamic data. Unlike arrays, the size of an ArrayList can grow or shrink automatically.
ArrayList belongs to the java.util package. So, we need to import it before using it.
We create an ArrayList using the following syntax:
Here, String is the data type stored in the ArrayList.
The add() method is used to add elements to the ArrayList.
Output: [Rahul, Amit, Neha]
This method inserts an element at a specific position.
The get() method returns the element at a specific index.
The set() method changes an element at a specific index.
The remove() method removes an element from the ArrayList.
You can also remove by value:
The size() method returns the number of elements in the ArrayList.
The contains() method checks whether an element exists in the ArrayList.
The clear() method removes all elements from the ArrayList.
The isEmpty() method checks if the ArrayList is empty.
indexOf() returns the first occurrence of an element. lastIndexOf() returns the last occurrence.
We can sort an ArrayList using Collections.sort().
The ArrayList class provides many useful methods like add(), remove(), get(), set(), size(), and more.
It is widely used in real-world Java applications because it is flexible and easy to use.
Tip: Use ArrayList when you need a resizable array and frequent data manipulation.