Which is the correct import statement for the arraylist class?

Java ArrayList

❮ Previous Next ❯

Java ArrayList

The ArrayList class is a resizable array, which can be found in the java.util package.

The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified (if you want to add or remove elements to/from an array, you have to create a new one). While elements can be added and removed from an ArrayList whenever you want. The syntax is also slightly different:

Example

Create an ArrayList object called cars that will store strings:

import java.util.ArrayList; // import the ArrayList class ArrayList cars = new ArrayList(); // Create an ArrayList object

If you don't know what a package is, read our Java Packages Tutorial.


ArrayList in Java

ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package.

Which is the correct import statement for the arraylist class?

Illustration:

Which is the correct import statement for the arraylist class?

Example: The following implementation demonstrates how to create and use an ArrayList.






// Java program to demonstrate the
// working of ArrayList in Java
import java.io.*;
import java.util.*;
class ArrayListExample {
public static void main(String[] args)
{
// Size of the
// ArrayList
int n = 5;
// Declaring the ArrayList with
// initial size n
ArrayList arrli
= new ArrayList(n);
// Appending new elements at
// the end of the list
for (int i = 1; i <= n; i++)
arrli.add(i);
// Printing elements
System.out.println(arrli);
// Remove element at index 3
arrli.remove(3);
// Displaying the ArrayList
// after deletion
System.out.println(arrli);
// Printing elements one by one
for (int i = 0; i < arrli.size(); i++)
System.out.print(arrli.get(i) + " ");
}
}
Output [1, 2, 3, 4, 5] [1, 2, 3, 5] 1 2 3 5

Since ArrayList is a dynamic array and we do not have to specify the size while creating it, the size of the array automatically increases when we dynamically add and remove items. Though the actual library implementation may be more complex, the following is a very basic idea explaining the working of the array when the array becomes full and if we try to add an item:

  • Creates a bigger-sized memory on heap memory (for example memory of double size).
  • Copies the current memory elements to the new memory.
  • New item is added now as there is bigger memory available now.
  • Delete the old memory.

Important Features:

  • ArrayList inherits AbstractList class and implements the List interface.
  • ArrayList is initialized by the size. However, the size is increased automatically if the collection grows or shrinks if the objects are removed from the collection.
  • Java ArrayList allows us to randomly access the list.
  • ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper class for such cases.
  • ArrayList in Java can be seen as a vector in C++.
  • ArrayList is not Synchronized. Its equivalent synchronized class in Java is Vector.

Let’s understand the Java ArrayList in depth. Look at the below image:

Which is the correct import statement for the arraylist class?

In the above illustration, AbstractList, CopyOnWriteArrayList, and the AbstractSequentialList are the classes that implement the list interface. A separate functionality is implemented in each of the mentioned classes. They are:

  1. AbstractList: This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.
  2. CopyOnWriteArrayList: This class implements the list interface. It is an enhanced version of ArrayList in which all the modifications(add, set, remove, etc.) are implemented by making a fresh copy of the list.
  3. AbstractSequentialList: This class implements the Collection interface and the AbstractCollection class. This class is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.

Constructors in the ArrayList

In order to create an ArrayList, we need to create an object of the ArrayList class. The ArrayList class consists of various constructors which allow the possible creation of the array list. The following are the constructors available in this class:

1. ArrayList(): This constructor is used to build an empty array list. If we wish to create an empty ArrayList with the name arr, then, it can be created as:

ArrayList arr = new ArrayList();

2. ArrayList(Collection c): This constructor is used to build an array list initialized with the elements from the collection c. Suppose, we wish to create an ArrayList arr which contains the elements present in the collection c, then, it can be created as:

ArrayList arr = new ArrayList(c);

3. ArrayList(int capacity): This constructor is used to build an array list with initial capacity being specified. Suppose we wish to create an ArrayList with the initial size being N, then, it can be created as:

ArrayList arr = new ArrayList(N);

Methods in Java ArrayList

Method Description
add(int index, Object element) This method is used to insert a specific element at a specific position index in a list.
add(Object o) This method is used to append a specific element to the end of a list.
addAll(Collection C) This method is used to append all the elements from a specific collection to the end of the mentioned list, in such an order that the values are returned by the specified collection’s iterator.
addAll(int index, Collection C) Used to insert all of the elements starting at the specified position from a specific collection into the mentioned list.
clear() This method is used to remove all the elements from any list.
clone() This method is used to return a shallow copy of an ArrayList.
contains?(Object o) Returns true if this list contains the specified element.
ensureCapacity?(int minCapacity) Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
forEach?(Consumer action) Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
get?(int index) Returns the element at the specified position in this list.
indexOf(Object O) The index the first occurrence of a specific element is either returned, or -1 in case the element is not in the list.
isEmpty?() Returns true if this list contains no elements.
lastIndexOf(Object O) The index of the last occurrence of a specific element is either returned or -1 in case the element is not in the list.
listIterator?() Returns a list iterator over the elements in this list (in proper sequence).
listIterator?(int index) Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
remove?(int index) Removes the element at the specified position in this list.
remove?(Object o) Removes the first occurrence of the specified element from this list, if it is present.
removeAll?(Collection c) Removes from this list all of its elements that are contained in the specified collection.
removeIf?(Predicate filter) Removes all of the elements of this collection that satisfy the given predicate.
removeRange?(int fromIndex, int toIndex) Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
retainAll?(Collection c) Retains only the elements in this list that are contained in the specified collection.
set?(int index, E element) Replaces the element at the specified position in this list with the specified element.
size?() Returns the number of elements in this list.
spliterator?() Creates a late-binding and fail-fast Spliterator over the elements in this list.
subList?(int fromIndex, int toIndex) Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
toArray() This method is used to return an array containing all of the elements in the list in the correct order.
toArray(Object[] O) It is also used to return an array containing all of the elements in this list in the correct order same as the previous method.
trimToSize() This method is used to trim the capacity of the instance of the ArrayList to the list’s current size.

Note: You can also create a generic ArrayList:

// Creating generic integer ArrayList ArrayList arrli = new ArrayList();

Let’s see how to perform some basics operations on the ArrayList as listed which we are going to discuss further alongside implementing every operation.

  • Adding element to List
  • Changing elements
  • Removing elements
  • Iterating elements

Operation 1: Adding Elements

In order to add an element to an ArrayList, we can use the add() method. This method is overloaded to perform multiple operations based on different parameters. They are as follows:

  • add(Object): This method is used to add an element at the end of the ArrayList.
  • add(int index, Object): This method is used to add an element at a specific index in the ArrayList.

Example:




// Java Program to Add elements to An ArrayList
// Importing all utility classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an Array of string type
ArrayList al = new ArrayList<>();
// Adding elements to ArrayList
// Custom inputs
al.add("Geeks");
al.add("Geeks");
// Here we are mentioning the index
// at which it is to be added
al.add(1, "For");
// Printing all the elements in an ArrayList
System.out.println(al);
}
}
Output: [Geeks, For, Geeks]

Operation 2: Changing Elements

After adding the elements, if we wish to change the element, it can be done using the set() method. Since an ArrayList is indexed, the element which we wish to change is referenced by the index of the element. Therefore, this method takes an index and the updated element which needs to be inserted at that index.

Example




// Java Program to Change elements in ArrayList
// Importing all utility classes
import java.util.*;
// main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an Arratlist object of string type
ArrayList al = new ArrayList<>();
// Adding elements to Arraylist
// Custom input elements
al.add("Geeks");
al.add("Geeks");
// Adding specifying the index to be added
al.add(1, "Geeks");
// Printing the Arraylist elements
System.out.println("Initial ArrayList " + al);
// Setting element at 1st index
al.set(1, "For");
// Printing the updated Arraylist
System.out.println("Updated ArrayList " + al);
}
}
Output: Initial ArrayList [Geeks, Geeks, Geeks] Updated ArrayList [Geeks, For, Geeks]

Operation 3: Removing Elements

In order to remove an element from an ArrayList, we can use the remove() method. This method is overloaded to perform multiple operations based on different parameters. They are as follows:

  • remove(Object): This method is used to simply remove an object from the ArrayList. If there are multiple such objects, then the first occurrence of the object is removed.
  • remove(int index): Since an ArrayList is indexed, this method takes an integer value which simply removes the element present at that specific index in the ArrayList. After removing the element, all the elements are moved to the left to fill the space and the indices of the objects are updated.

Example




// Java program to Remove Elements in ArrayList
// Importing all utility classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an object of arraylist class
ArrayList al = new ArrayList<>();
// Adding elements to ArrayList
// Custom addition
al.add("Geeks");
al.add("Geeks");
// Adding element at specific index
al.add(1, "For");
// Printing all elements of ArrayList
System.out.println("Initial ArrayList " + al);
// Removing element from above ArrayList
al.remove(1);
// Printing the updated Arraylist elements
System.out.println("After the Index Removal " + al);
// Removing this word element in ArrayList
al.remove("Geeks");
// Now printing updated ArrayList
System.out.println("After the Object Removal "
+ al);
}
}
Output: Initial ArrayList [Geeks, For, Geeks] After the Index Removal [Geeks, Geeks] After the Object Removal [Geeks]

Operation 4: Iterating the ArrayList

There are multiple ways to iterate through the ArrayList. The most famous ways are by using the basic for loop in combination with a get() method to get the element at a specific index and the advanced for loop.

Example




// Java program to Iterate the elements
// in an ArrayList
// Importing all utility classes
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an Arraylist of string type
ArrayList al = new ArrayList<>();
// Adding elements to ArrayList
// using standard add() method
al.add("Geeks");
al.add("Geeks");
al.add(1, "For");
// Using the Get method and the
// for loop
for (int i = 0; i < al.size(); i++) {
System.out.print(al.get(i) + " ");
}
System.out.println();
// Using the for each loop
for (String str : al)
System.out.print(str + " ");
}
}
Output: Geeks For Geeks Geeks For Geeks

Must Read: Array vs ArrayList in Java

Which is the correct import statement for the arraylist class?




Article Tags :
Java
Technical Scripter
Java - util package
Java-ArrayList
Java-Collections
java-list
Practice Tags :
Java
Java-Collections

Why ArrayList is better than Array?

The limitation with array is that it has a fixed length so if it is full you cannot add any more elements to it, likewise if there are number of elements gets removed from it the memory consumption would be the same as it doesn’t shrink.

On the other ArrayList can dynamically grow and shrink after addition and removal of elements (See the images below). Apart from these benefits ArrayList class enables us to use predefined methods of it which makes our task easy. Let’s see the diagrams to understand the addition and removal of elements from ArrayList and then we will see the programs.

Adding Element in ArrayList at specified position:

Which is the correct import statement for the arraylist class?

Removing Element from ArrayList:

Which is the correct import statement for the arraylist class?

There is a list of several tutorials on ArrayList at the end of this guide, refer it to understand and learn ArrayList concept fully.

Java ArrayList

Which is the correct import statement for the arraylist class?

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

ConstructorDescription
ArrayList()It is used to build an empty array list.
ArrayList(Collection 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

MethodDescription
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 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 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[] 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 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 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 c)It is used to sort the elements of the list on the basis of specified comparator.
Spliterator spliterator()It is used to create spliterator over the elements in a list.
List 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 c) method: [Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat] After invoking addAll(int index, Collection 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

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


← prev next →


Java ArrayList Class

In this tutorial, we will learn about the ArrayList class in Java. We will learn about different operations and methods of the arraylist with the help of examples.

The ArrayList class of the Java collections framework provides the functionality of resizable-arrays.

It implements the List interface.

Which is the correct import statement for the arraylist class?
Java ArrayList Implementation