
ArrayList in Java is a dynamic array implementation that belongs to the Java Collections Framework. This is a big array that grows on its own as more elements are added to it.
ArrayLists come from the java.util package and are quite commonly used for their ease of use and flexibility. They offer flexibility in that you do not need to determine the size of the ArrayList at the time of its creation, which is similar to standard arrays in Java. So, it is much more flexible than the traditional array. It is like the Vector in C++.
The ArrayList in Java can also have duplicate elements. It implements the List interface so that we can use all the methods of the List interface here. The ArrayList maintains the insertion order internally.
It inherits the AbstractList class and implements List interface.
The important points about the Java ArrayList class are:
As shown in the above diagram, the Java ArrayList class extends AbstractList class which implements the List interface. The List interface extends the Collection and Iterable interfaces in hierarchical order.
Let's see the declaration for java.util.ArrayList class.
public class ArrayList<E>: Introduces the ArrayList class as a generic one with a type parameter E which is the type of the elements stored in the ArrayList. The type paramter E enables the ArrayList to store objects of any reference type.
extends AbstractList<E>: Means that the ArrayList class is a subclass of the AbstractList class. AbstractList implements the Skeletal aspect of the List interface, providing almost all of its methods.
implements List<E>: Indicates that the ArrayList class implements the List interface. The List interface describes operations for lists and extends the Collection interface.
implements RandomAccess: Indicates that the RandomAccess marker interface is implemented by the ArrayList class. This interface is a flag for classes that provide fast (constant time) random access to their elements.
implements Cloneable: States that the ArrayList class implements the Cloneable marker interface. This interface signifies that ArrayList instances can be cloned using the clone() method.
implements Serializable: This shows that the ArrayList class implements the Serializable marker interface. This interface makes instances of the ArrayList class serializable (converted into a byte stream) for storage or transmission.
| Constructor | Description |
|---|---|
| ArrayList() | It is used to build an empty array list. |
| ArrayList(Collection<? extends E> c) | It is used to build an array list that is initialized with the elements of the collection c. |
| ArrayList(int capacity) | It is used to build an array list that has the specified initial capacity. |
| Method | Description |
|---|---|
| void add(int index, E element) | It is used to insert the specified element at the specified position in a list. |
| boolean add(E e) | It is used to append the specified element at the end of a list. |
| boolean addAll(Collection<? extends E> c) | It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. |
| boolean addAll(int index, Collection<? extends E> c) | It is used to append all the elements in the specified collection, starting at the specified position of the list. |
| void clear() | It is used to remove all of the elements from this list. |
| void ensureCapacity(int requiredCapacity) | It is used to enhance the capacity of an ArrayList instance. |
| E get(int index) | It is used to fetch the element from the particular position of the list. |
| boolean isEmpty() | It returns true if the list is empty, otherwise false. |
| Iterator() | Returns an iterator over the elements in the ArrayList in proper sequence. Allows sequential access to the elements in the ArrayList. |
| listIterator() | Returns a list iterator over the elements in the ArrayList in proper sequence. Allows bidirectional access to the elements in the ArrayList, including adding, removing, and modifying elements during iteration. |
| int lastIndexOf(Object o) | It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element. |
| Object[] toArray() | It is used to return an array containing all of the elements in this list in the correct order. |
| <T> T[] toArray(T[] a) | It is used to return an array containing all of the elements in this list in the correct order. |
| Object clone() | It is used to return a shallow copy of an ArrayList. |
| boolean contains(Object o) | It returns true if the list contains the specified element. |
| int indexOf(Object o) | It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element. |
| E remove(int index) | It is used to remove the element present at the specified position in the list. |
| boolean remove(Object o) | It is used to remove the first occurrence of the specified element. |
| boolean removeAll(Collection<?> c) | It is used to remove all the elements from the list. |
| boolean removeIf(Predicate<? super E> filter) | It is used to remove all the elements from the list that satisfies the given predicate. |
| protected void removeRange(int fromIndex, int toIndex) | It is used to remove all the elements lies within the given range. |
| void replaceAll(UnaryOperator<E> operator) | It is used to replace all the elements from the list with the specified element. |
| void retainAll(Collection<?> c) | It is used to retain all the elements in the list that are present in the specified collection. |
| E set(int index, E element) | It is used to replace the specified element in the list, present at the specified position. |
| void sort(Comparator<? super E> c) | It is used to sort the elements of the list on the basis of the specified comparator. |
| Spliterator<E> spliterator() | It is used to create a spliterator over the elements in a list. |
| List<E> subList(int fromIndex, int toIndex) | It is used to fetch all the elements that lies within the given range. |
| int size() | It is used to return the number of elements present in the list. |
| void trimToSize() | It is used to trim the capacity of this ArrayList instance to be the list's current size. |
Before JDK 1.5, the Java Collections Framework was a non-generic one, which meant that type safety wasn't guaranteed, and manual type casting was required when retrieving elements from collections.
In this non-generic ArrayList, you could add elements of any type and the compiler did not enforce type safety. For example, you could add a String followed by an Integer without compile-time checks.
With the introduction of generics in Java 5 (JDK 1.5), the Collections Framework became generic. Generics allow you to specify the type of elements a collection can hold at compile time, providing type safety and eliminating the need for explicit type casting. Here's an example of creating a generic ArrayList:Let's see the new generic example of creating a Java collection.
In this generic ArrayList, the type parameter
Output:
[Mango, Apple, Banana, Grapes]
Iterating through an ArrayList using an Iterator in Java is a common operation that allows you to traverse the list's elements sequentially. Iterators provide a safe and efficient way to access elements in a collection, especially when you want to perform operations like removing elements during iteration. Let's see an example of traversing ArrayList elements using the Iterator interface.
Output:
Mango Apple Banana Grapes
Iterating through an ArrayList using a for-each loop, also known as an enhanced for loop, provides a concise and readable way to access elements in the list sequentially. This approach simplifies the code and is especially useful when you only need to iterate through the elements without requiring the index or performing complex operations. Let's see an example to traverse the ArrayList elements using the for-each loop.
Output:
Mango Apple Banana Grapes
You can retrieve and modify an ArrayList using the get() and set() methods.
Using get() method:
Using set() method:
Output:
Returning element: Apple Mango Dates Banana Grapes
The java.util package provides a utility class Collections, which has the static method sort(). Using the Collections.sort() method, we can easily sort the ArrayList.
Output:
Apple Banana Grapes Mango Sorting numbers... 1 11 21 51
There are various ways to traverse the collection elements:
Let's see an example to traverse the ArrayList elements through other ways
Output:
Traversing list through List Iterator: Ajay Ravi Vijay Ravi Traversing list through for loop: Ravi Vijay Ravi Ajay Traversing list through forEach() method: Ravi Vijay Ravi Ajay Traversing list through forEachRemaining() method: Ravi Vijay Ravi Ajay
ArrayLists can store objects of user-defined classes, providing flexibility and scalability in managing collections of custom data types. This capability allows developers to create collections tailored to their specific application requirements.
When using user-defined class objects in ArrayLists, each element in the ArrayList represents an instance of the user-defined class. For example, consider a scenario where a Student class represents individuals with attributes such as name, age, and rollno. We can create an ArrayList to store instances of the Sudent class:
Let's see an example where we store Student class objects in an array list.
Output:
101 Sonoo 23
102 Ravi 21
103 Hanumat 25
Serialization and deserialization in Java are processes used to convert objects into byte streams for storage or transmission and then reconstruct the objects from those byte streams, respectively. This mechanism allows objects to be saved to files, sent over networks, or stored in databases.
Let's see an example of serialising an ArrayList object and then deserialising it.
Output:
[Ravi, Vijay, Ajay]
Here, we see different ways to add an element.
Output:
Initial list of elements: [] After invoking add(E e) method: [Ravi, Vijay, Ajay] After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay] After invoking addAll(Collection<? extends E> c) method: [Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat] After invoking addAll(int index, Collection<? extends E> c) method: [Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
Here, we see different ways to remove an element.
Output:
An initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav] After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav] After invoking remove(index) method: [Ajay, Anuj, Gaurav] Updated list : [Ajay, Anuj, Gaurav, Ravi, Hanumat] After invoking removeAll() method: [Ajay, Anuj, Gaurav] After invoking removeIf() method: [Anuj, Gaurav] After invoking clear() method: []
retainAll() method in Java ArrayList is used to retain only the elements in the ArrayList that are also present in another collection, typically another ArrayList. In other words, it removes all elements from the current ArrayList that are not contained in the specified collection.
Output:
iterating the elements after retaining the elements of al2 Ravi
isEmpty() method in Java ArrayList is used to check if the ArrayList is empty, i.e., it returns true if the ArrayList contains no elements and false otherwise.
Output:
Is ArrayList Empty: true After Insertion Is ArrayList Empty: false
Let's see an ArrayList example where we are adding books to the list and printing all the books.
Output:
101 Let us C Yashwant Kanetkar BPB 8 102 Data Communications and Networking Forouzan Mc Graw Hill 4 103 Operating System Galvin Wiley 6
Size and capacity of an array list are the two terms that beginners find confusing. ArrayList handles a variable size of elements through elements being added or removed, making it flexible on collections. The length of an ArrayList refers to the number of elements to be stored in it, which you can obtain by calling the size() method. This size is automatically adjusted when elements are added or removed.
An Array List capacity means the maximum number of elements it can keep before having to be resized. Initially, an ArrayList's capacity is defined by the constructor used to create it, or by the default capacity in the event no constructor is defined. When the total numbers of objects in ArrayList exceed the current capacity, the ArrayList automatically reallocates and increases its capacity to carry more objects, hence efficient storage and whimpering. The size of the ArrayList can be retrieved using the capacity() method.
Let's understand it in this section with the help of some examples. Consider the following code snippet.
Output:
The size of the array is: 0
Explanation: The output makes sense as we have not done anything with the array list. Now observe the following program.
Output:
The size of the array is: 0
Explanation: We see that the size is still 0, and the reason behind this is the number 10 represents the capacity no the size. In fact, the size represents the total number of elements present in the array. As we have not added any element, therefore, the size of the array list is zero in both programs.
Imagine you have a box called an ArrayList. This box has a special property called capacity, which tells you how many items it can hold. Let's say the capacity of this box is 10.
Now, you start putting items into this box, like toys. Every time you put a toy inside, you check if the number of toys in the box (that's called the size) is equal to the capacity. If it is, it means the box is full, and you need a bigger box to put more toys in.
So, until you've put 10 toys in the box, the capacity stays at 10. But as soon as you try to put an 11th toy inside, you realize the box is full, and you need a bigger box. In our case, since the box can only hold 10 toys, you need to get a new box with a bigger capacity.
Now, remember, there are two scenarios:
In the first scenario, you start with a default box that can hold 10 toys. You don't specify the capacity; it's just the default.
In the second scenario, you explicitly say, "I want a box with a capacity of 10 toys." So, right from the start, you get a box that can hold exactly 10 toys.
But the process is the same in both cases: you keep adding toys, and if the box gets full, you get a bigger one.
Note: There is no standard method to tell how the capacity increases in the array list. In fact, the way the capacity increases varies from one GDK version to the other version. Therefore, it is required to check how capacity increases code is implemented in the GDK. There is no pre-defined method in the ArrayList class that returns the capacity of the array list. Therefore, for better understanding, use the capacity() method of the Vector class. The logic of the size and capacity are the same in the ArrayList and Vector classes.
We request you to subscribe our newsletter for upcoming updates.