ArrayList is a widely used data structure in the Java programming language. It is a part of the Java Collection Framework and is an implementation of the List interface. ArrayList provides a dynamic array, which allows for fast and efficient data retrieval, insertion, and deletion. In this blog post, we will discuss what ArrayList is. How it works. And how to use it in Java, including examples of all the available methods.
What is ArrayList in Java?
An ArrayList is an ordered collection of elements that allows for duplicate values. ArrayList is implemented using an array, which means that it has a fixed size. However, ArrayList provides a dynamic array, which means that the size of this ArrayList can grow or shrink as needed. This makes it a powerful tool for working with collections of objects, as it allows for fast and efficient data retrieval, insertion, and deletion.
Why use ArrayList in Java?
ArrayList is useful in situations where we need to work with a collection of objects and need to maintain the order of the elements. It is particularly useful when we need to perform operations such as adding and removing elements frequently.
ArrayList is also useful when we do not know the size of the collection in advance. And also need a dynamic array that can grow or shrink as needed. It is a good alternative for arrays when we need to add or remove elements from the collection frequently. It eliminates the need to manually resize the array and manage the underlying data structure.
How to use ArrayList in Java?
Using ArrayList in Java is relatively simple. To create an ArrayList, we first need to import the java.util
package, which contains the ArrayList class.
Here is an example of creating an ArrayList and adding data to it:
import java.util.ArrayList;
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
The output of the example above is:
[1, 2, 3]
Once we create an ArrayList, we can add data to it using the add()
method. In the example above, we are adding three elements to the ArrayList.
We can also retrieve data from an ArrayList using the get()
method. For example, to retrieve the second element in the ArrayList, we can use the following code:
Integer value = list.get(1);
The output of the example above is:
2
ArrayList also provides several other useful methods such as remove()
, clear()
, and size()
to manipulate the elements in the list. These methods are already discussed in the earlier post HashMap in Java.
ArrayList also provides other useful methods such as add(index, element)
, set(index, element)
and indexOf(element)
to access the elements in the list.