ArrayList is a class in Java that implements the List interface and provides a dynamic array to store elements. It is similar to an array but has the ability to grow and shrink in size as needed.
One of the main advantages of using ArrayList over a traditional array is its flexibility in terms of resizing. With a traditional array, once the size is set, it cannot be changed. However, ArrayList can automatically increase or decrease its size as elements are added or removed.
To use an ArrayList, it must first be imported from java.util package.
import java.util.ArrayList;
Then, it can be declared and initialized as follows:
ArrayList<String> fruits = new ArrayList<String>();
The generic type <String> in the above example specifies that the ArrayList will only contain elements of the String type. This can be changed to any other data type as needed.
Elements can be added to the ArrayList using the add() method. For example:
fruits.add("apple");
fruits.add("orange");
fruits.add("mango");
Elements can also be inserted at a specific index using the add() method with an index parameter. For example:
fruits.add(1, "banana");
This will insert "banana" at index 1, pushing all other elements to the right.
Elements can be removed from the ArrayList using the remove() method. For example:
fruits.remove("mango");
This will remove the first occurrence of "mango" from the list.
The size of the ArrayList can be determined using the size() method,
int fruitCount = fruits.size();
Individual elements can be accessed using the get() method with an index parameter. For example:
String secondElement = fruits.get(1);
In addition to these basic methods, ArrayList also provides many other useful methods such as contains() to check if an element exists in the list, indexOf() to find the index of a specific element, and sort() to sort the elements in the list.
Overall, ArrayList is a powerful and versatile class in Java that can be used to store and manage a dynamic list of elements. It is a useful alternative to traditional arrays and is widely used in many Java applications.