Javatpoint Logo
Javatpoint Logo

Java ArrayList

Java ArrayList class hierarchy

Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no size limit. We can add or remove elements anytime. So, it is much more flexible than the traditional array. It is found in the java.util package. It is like the Vector in C++.

The ArrayList in Java can have the duplicate elements also. It implements the List interface so we can use all the methods of List interface here. The ArrayList maintains the insertion order internally.

It inherits the AbstractList class and implements List interface.

The important points about Java ArrayList class are:

  • Java ArrayList class can contain duplicate elements.
  • Java ArrayList class maintains insertion order.
  • Java ArrayList class is non synchronized.
  • Java ArrayList allows random access because array works at the index basis.
  • In ArrayList, manipulation is little bit slower than the LinkedList in Java because a lot of shifting needs to occur if any element is removed from the array list.

Hierarchy of ArrayList class

As shown in the above diagram, Java ArrayList class extends AbstractList class which implements List interface. The List interface extends the Collection and Iterable interfaces in hierarchical order.

ArrayList class declaration

Let's see the declaration for java.util.ArrayList class.

Constructors of ArrayList

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.

Methods of ArrayList

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()
listIterator()
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 specified comparator.
Spliterator<E> spliterator() It is used to create spliterator over the elements in a list.
List<E> subList(int fromIndex, int toIndex) It is used to fetch all the elements 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.

Java Non-generic Vs. Generic Collection

Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.

Java new generic collection allows you to have only one type of object in a collection. Now it is type safe so typecasting is not required at runtime.

Let's see the old non-generic example of creating java collection.

Let's see the new generic example of creating java collection.

In a generic collection, we specify the type in angular braces. Now ArrayList is forced to have the only specified type of objects in it. If you try to add another type of object, it gives compile time error.

For more information on Java generics, click here Java Generics Tutorial.

Java ArrayList Example

Test it Now

Output:

[Mango, Apple, Banana, Grapes]

Iterating ArrayList using Iterator

Let's see an example to traverse ArrayList elements using the Iterator interface.

Test it Now

Output:

Mango
Apple
Banana
Grapes

Iterating ArrayList using For-each loop

Let's see an example to traverse the ArrayList elements using the for-each loop

Output:

Test it Now
Mango
Apple
Banana
Grapes

Get and Set ArrayList

The get() method returns the element at the specified index, whereas the set() method changes the element.

Test it Now

Output:

Returning element: Apple
Mango
Dates
Banana
Grapes

How to Sort ArrayList

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

Ways to iterate the elements of the collection in Java

There are various ways to traverse the collection elements:

  1. By Iterator interface.
  2. By for-each loop.
  3. By ListIterator interface.
  4. By for loop.
  5. By forEach() method.
  6. By forEachRemaining() method.

Iterating Collection through remaining ways

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


User-defined class objects in Java ArrayList

Let's see an example where we are storing Student class object in an array list.


Output:

       101 Sonoo 23
       102 Ravi 21
       103 Hanumat 25

Java ArrayList Serialization and Deserialization Example

Let's see an example to serialize an ArrayList object and then deserialize it.

Output:

       [Ravi, Vijay, Ajay]

Java ArrayList example to add elements

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]

Java ArrayList example to remove elements

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: []

Java ArrayList example of retainAll() method

Output:

       iterating the elements after retaining the elements of al2
       Ravi

Java ArrayList example of isEmpty() method

Output:

Is ArrayList Empty: true
After Insertion
Is ArrayList Empty: false

Java ArrayList Example: Book

Let's see an ArrayList example where we are adding books to list and printing all the books.

Test it Now

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

Related Topics

How to Sort ArrayList in Java

Difference between Array and ArrayList

When to use ArrayList and LinkedList in Java

Difference between ArrayList and LinkedList

Difference between ArrayList and Vector

How to Compare Two ArrayList in Java

How to reverse ArrayList in Java

When to use ArrayList and LinkedList in Java

How to make ArrayList Read Only

Difference between length of array and size() of ArrayList in Java

How to Synchronize ArrayList in Java

How to convert ArrayList to Array and Array to ArrayList in java

Array vs ArrayList in Java

How to Sort Java ArrayList in Descending Order

How to remove duplicates from ArrayList in Java

Next TopicJava LinkedList




Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA