In computer programming, an array list is an adjustable (expanding) array that is used to store a collection of objects. It allows users to dynamically add or remove objects, as opposed to the regular arrays which stay the same in size, once created. It is one of the interfaces of the Java Collections Framework that is most utilised in the management of objects’ lists. It is also easy to add elements, delete them or remove them from certain places within the ArrayList which can be an advantage in a great number of situations.
This blog covers everything concerning ArrayList in Java, its creation, important features and more importantly how it can be used in comparison with arrays. We shall look into some methods of the class as well as the advantages and disadvantages of the ArrayList.
What is an ArrayList in Java?
An array list is a part of the Java Collections framework, which is implemented with the List interface. Its features include the ability to resize itself, meaning that it does grow or diminish depending on the amount of its elements. For example, whereas the size of the arrays is fixed at the time of creation, with the List, however, it increases or decreases according to need.
Internally, an ArrayList implements an array for storing elements. Once the array reaches its limits, it forms a new array that is bigger and places the previous elements into this new array. This dynamic resizing makes ArrayList highly flexible for managing data collections where the number of elements can change frequently.
ArrayList also implements various methods from the List interface, like add(), remove(), and get(), which make it easy to manipulate elements. It also allows duplicate elements and maintains the insertion order, ensuring that the sequence of items is preserved during operations.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Creating an ArrayList
To use ArrayList in Java, one must import the java.util.ArrayList package first. This package comprises the ArrayList class which is a depository of the Java collection framework. In this package, there is an ArrayList which can be employed within the program.
The general syntax for creating an ArrayList in Java is:
ArrayList<DataType> arrayListName = new ArrayList<DataType>();
ArrayList<DataType>: It is used to create an ArrayList of specific types such as String, Integer, etc.
arrayListName: It represents the name of the ArrayList object.
new ArrayList<DataType>(): It is used for creating the new instance of the ArrayList.
Example of Creating an ArrayList
In this example, the ArrayList stores and displays a list of fruits. The elements are displayed in the order they were added.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Creating an ArrayList of String type
ArrayList<String> fruits = new ArrayList<String>();
// Adding elements to the ArrayList
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
// Printing the ArrayList
System.out.println(fruits);
}
}
Explanation
The import java.util.ArrayList; statement imports the ArrayList class.
The ArrayList<String> fruits create an ArrayList that stores strings.
The add() method adds elements (“Apple”, “Banana”, and “Mango”) to the ArrayList.
Output
[Apple, Banana, Mango]
Important Features of ArrayList in Java
Resizable Array: Unlike a regular array, an ArrayList can dynamically grow or shrink as needed. This allows for more flexibility in managing data collections.
Maintains Insertion Order: Elements in an ArrayList are stored in the order they are added. It maintains this order throughout its operations.
Allows Duplicates: You can store duplicate elements in an ArrayList, which means the same value can appear more than once.
Random Access: Users can view the elements by index with the usage of the get() method and this is very convenient because the element retrieval is made faster.
Implements the List Interface: ArrayList implements the List interface, therefore it has additional methods such as add and remove, size, and contains which are very helpful.
Non-Synchronized: By default, ArrayList is not synchronised, and this is a great advantage when usage is meant to be single-threaded. However, it makes it unsafe for multi-threaded applications.
Can Store Null Values: ArrayList can store null values,, as such it can contain one or many null entries in the list.
Auto-Resizing: When the number of Elements crosses the present limit of an ArrayList then the size of the ArrayList is automatically increased by 50% of the existing space.
In Java, the ArrayList has a number of different constructors that provide assistance in the creation of the array list in several different ways as shall be determined by the need. Constructor is a special type of method, which is used to specify the values of an object in focus. In the case of ArrayList, the constructors specify the capacity of the new ArrayList or elements of the new ArrayList are taken from others already present.
Here are the commonly used constructors of ArrayList:
Default Constructor
This creates an empty ArrayList with a default capacity.
Syntax:
ArrayList<DataType> arrayList = new ArrayList<>();
Constructor with Initial Capacity:
This constructor allows you to define the initial capacity of the ArrayList. This can be helpful if you know the approximate size of the list in advance.
ArrayList<DataType> arrayList = new ArrayList<>(int initialCapacity);
Constructor with Another Collection
This constructor creates an ArrayList containing all the elements of a specified collection (e.g., another ArrayList, Set, etc.). The order of the elements in the new list will be the same as the collection provided.
Syntax
ArrayList<DataType> arrayList = new ArrayList<>(Collection<? extends DataType> collection);
Example: Using the Constructor with Initial Capacity
In the example below, we have passed the ‘5’ as a parameter of the ArrayList constructor. Here, ‘5’ represents the initial capacity of the ‘numbers’ ArrayList.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Creating an ArrayList with an initial capacity of 5
ArrayList<Integer> numbers = new ArrayList<>(5);
// Adding elements to the ArrayList
numbers.add(10);
numbers.add(20);
numbers.add(30);
// Printing the ArrayList
System.out.println(numbers);
}
}
Explanation:
The new ArrayList<>(5) creates an ArrayList with a preliminary capacity of five, meaning the list can preserve as many as 5 elements earlier than resizing is needed.
The add() method adds elements (10, 20, and 30) to the ArrayList.
Output:
[10, 20, 30]
Basic Operations on ArrayList
The Java ArrayList offers several techniques to perform its basic actions like adding, retrieving, updating, and deleting elements. Let’s explore each operation in detail with examples.
Add Elements
For putting elements into an ArrayList, we will use the add() method. We need to pass a single element as a parameter of the add() method, to be added at the end of the list.
Example
In the example below, we have created the ‘colors’ ArrayList of string data type. After that, we used the add() method to insert ‘Red’ and ‘Blue’ strings at the end of the list. Next, we have inserted the “Green” string at index 1.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> colors = new ArrayList<>();
colors.add("Red"); // Adding at the end
colors.add("Blue");
colors.add(1, "Green"); // Adding at index 1
System.out.println(colors);
}
}
Output
[Red, Green, Blue]
Access Elements
Gaining access to elements from the ArrayList is the same as Array. The get() method can be used to access ArrayList elements through their index values. However, you should remember that the index starts from zero, but no longer from 1.
Example
In the example code below, we have defined the ‘animals’ ArrayList, which incorporates three animal names in the string data types. After that, we used the get() method to access the elements from the 0 and 2 indexes.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> animals = new ArrayList<>();
animals.add("Dog");
animals.add("Cat");
animals.add("Horse");
// Accessing elements by index
System.out.println(animals.get(0)); // First element
System.out.println(animals.get(2)); // Third element
}
}
Output
Dog
Horse
Change Elements
We can use the ArrayList.set() method to insert an element in the referenced list. Using the set() method, users can update the detail on the specific index with a new value.
Example
Here, we use the set() method to exchange the element at index 1. We replace the “Banana” string with the “Orange” string.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
// Changing the element at index 1
fruits.set(1, "Orange");
System.out.println(fruits);
}
}
Output
[Apple, Orange, Mango]
Remove Elements
We can use the remove() method for removing particular elements from the ArrayList. To remove specific elements, users can use the index or element value.
Example
Here, you can use the remove(2) method, which removes the element at index 2 (“C++”). On the other hand, remove(“Python”) removes “Python” from the list.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Python");
languages.add("C++");
// Removing element at index 2
languages.remove(2);
// Removing the element "Python"
languages.remove("Python");
System.out.println(languages);
}
}
Output
[Java]
Add Elements Between Two Numbers
Users can use the add(index, element) approach to feature the element at a selected position. The index shows the position where the ‘element’ will be added. This way you can maintain a specific order in the ArrayList.
Example
Here, we have used the add() method to add ‘20’ at index 1.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(30);
// Adding 20 between 10 and 30
numbers.add(1, 20);
System.out.println(numbers);
}
}
Output
[10, 20, 30]
Sorting ArrayList
In Java, you could use the Collections.sort() method for sorting any kind of collection consisting of the ArrayList. This approach lets you set up the elements in increasing or decreasing order.
Example
In the code below, we’ve used the Collections.sort(marks) method to sort the list in increasing order.
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> marks = new ArrayList<>();
marks.add(85);
marks.add(40);
marks.add(75);
// Sorting the ArrayList
Collections.sort(marks);
System.out.println(marks);
}
}
Output
[40, 75, 85]
Getting the Size of ArrayList
Developers can use the ArrayList.Size() approach to get the scale of the list, which represents the range of elements within the ArrayList.
Example
Here, you can get the number of elements in ArrayList with the help of cities.size(), which is 3.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cities = new ArrayList<>();
cities.add("New York");
cities.add("London");
cities.add("Tokyo");
// Getting the size of the ArrayList
System.out.println(cities.size());
}
}
Output
3
Iterate through an ArrayList
There are numerous approaches to iterate through an ArrayList, consisting of the use of a for loop, for-each loop or Iterator.
Example (Using a For-Each Loop)
In this case, a for-each loop is used to iterate via the ArrayList and then we can print each element through iteration.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<>();
cars.add("Tesla");
cars.add("BMW");
cars.add("Audi");
// Iterating through the ArrayList
for (String car : cars) {
System.out.println(car);
}
}
}
Output
Tesla
BMW
Audi
User-defined class objects in Java ArrayList
An ArrayList in Java can not only hold primitive data types but also user-defined data types. This is more helpful since one can create objects of classes and store these objects in an ArrayList. The procedure consists of defining a class, instantiating the class and then putting its instances into the ArrayList.
Define a user class with some attributes and methods.
Create an ArrayList of that class type.
Add instances of the class to the ArrayList.
Example
In this case, we will create a Person class and we will store its objects in an ArrayList.
import java.util.ArrayList;
class Person {
String name;
int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method to display person details
public void displayPersonInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
// Creating an ArrayList of Person objects
ArrayList<Person> people = new ArrayList<>();
// Adding Person objects to the ArrayList
people.add(new Person("John", 25));
people.add(new Person("Jane", 30));
people.add(new Person("Mike", 22));
// Displaying Person details using a loop
for (Person person : people) {
person.displayPersonInfo();
}
}
}
Explanation
We create a Person class with two fields: name and age.
The Person class has a constructor that initialises these fields, and a method displayPersonInfo() to print the person’s details.
We then create an ArrayList of type Person called people, and add new Person objects to it using the add() method.
A for-each loop is used to iterate through the ArrayList and call the displayPersonInfo() method on each Person object.
Can only store objects (Wrapper classes for primitives).
Flexibility
Less flexible due to fixed size.
More flexible due to resizable nature.
Memory Management
Memory is allocated at creation.
Memory is dynamically managed, increases as elements are added.
Methods Available
No built-in methods like add() or remove().
Provides various methods such as add(), remove(), get(), etc.
Performance
Faster when working with a fixed number of elements.
Slightly slower due to dynamic resizing, but more flexible.
Type Safety
Can store multiple types of elements using an Object array.
Type-safe with Generics, can store elements of specific types only.
Iteration
Need to manually iterate using loops.
Can use enhanced for-loops, iterators, and streams for easier iteration.
Multidimensional Support
Supports multidimensional arrays.
ArrayList does not directly support multidimensional structures, but you can create an ArrayList of ArrayLists.
Pros and Cons of ArrayList
Pros
Dynamic Resizing: Automatically resizes when elements are added or removed, making it more flexible than arrays.
Easy to Use: Provides built-in methods such as add(), remove(), and get(), simplifying operations on collections.
Maintains Insertion Order: Elements are stored in the order they are added, which helps in maintaining data sequence.
Random Access: Allows quick access to elements using the get() method, thanks to its internal array-based structure.
Supports Generics: Ensures type safety by allowing you to specify the type of elements the list can store.
Cons
Slower Performance for Certain Operations: Inserting or removing elements from the middle of the list can be slower due to shifting elements.
Increased Memory Usage: Resizing the ArrayList requires additional memory, especially when it grows beyond its current capacity.
Not Synchronised: By default, ArrayList is not thread-safe, which can cause issues in multi-threaded applications.
Stores Only Objects: Cannot store primitive data types directly, requiring the use of wrapper classes, which adds some overhead.
Performance Impact During Resizing: When the internal array needs to grow, it can cause a temporary performance hit due to copying elements to a new array.
Methods of ArrayList Class
Method Name
Description
Parameters
Return Type
add()
Adds an element to the end of the list.
E element
boolean
addAll()
Adds all elements from the specified collection to the list.
Collection<? extends E> c
boolean
clear()
Removes all elements from the list.
None
void
clone()
Creates a shallow copy of the ArrayList.
None
Object
contains()
Checks if the list contains the specified element.
Object o
boolean
ensureCapacity()
Ensures the list has enough capacity to hold a specified number of elements.
int minCapacity
void
forEach()
Performs the specified action for each element in the list.
Consumer<? super E> action
void
get()
Returns the element at the specified index.
int index
E
indexOf()
Returns the index of the first occurrence of the specified element.
Object o
int
isEmpty()
Checks if the list is empty.
None
boolean
iterator()
Returns an iterator for the elements in the list.
None
Iterator<E>
lastIndexOf()
Returns the index of the last occurrence of the specified element.
Object o
int
listIterator()
Returns a list iterator starting at the specified index.
int index (optional)
ListIterator<E>
remove()
Removes the element at the specified index or object from the list.
int index or Object o
E or boolean
removeAll()
Removes all elements that are present in the specified collection.
Collection<?> c
boolean
removeIf()
Removes elements that satisfy the specified predicate.
Predicate<? super E> filter
boolean
replaceAll()
Replaces each element of the list with the result of applying the specified operator.
UnaryOperator<E> operator
void
retainAll()
Retains only the elements that are contained in the specified collection.
Collection<?> c
boolean
set()
Replaces the element at the specified index with a new element.
int index, E element
E
size()
Returns the number of elements in the list.
None
int
sort()
Sorts the list according to the specified comparator.
Comparator<? super E> c
void
spliterator()
Creates a Spliterator for the elements in the list.
None
Spliterator<E>
subList()
Returns a view of the list between the specified fromIndex and toIndex.
int fromIndex, int toIndex
List<E>
toArray()
Converts the list into an array.
No parameters or T[] a
Object[] or T[]
trimToSize()
Trims the capacity of the list to its current size.
In general, the ArrayList class in Java is a data type that provides high flexibility and is highly extensible, thanks to permitting resizing and having the methods included for the convenient handling of the data. It is particularly beneficial for applications that want to use dynamic arrays because of its ability to random access elements, insertion order, and custom-defined objects.
On the contrary, it comes with some disadvantages that developers must be really cautious about, for example, performing some operations like removing or inserting elements or records at the middle of the list is not very efficient. Even so, its flexibility and simplicity of use dictate that ArrayList is the perfect choice when it comes to storing dynamic arrays or collections in Java. With this detailed guide, you are ready to use ArrayList in your Java applications. Check out Hero Vired’s Certificate Program in Full Stack Development if you want to master Java.
FAQs
What is the difference between ArrayList and an array?
An ArrayList is dynamic, while an array has a fixed size.
Can ArrayList store primitive types?
No, ArrayList can only store objects; you need to use wrapper classes for primitives.
How do I access elements in an ArrayList?
You can use the get(index) method to access elements by their index.
Is ArrayList synchronised?
No, ArrayList is not synchronised by default and is not thread-safe.
Can we store null values in ArrayList?
Yes, ArrayList allows storing null values.
How do I remove an element from an ArrayList?
You can remove elements using the remove(index) or remove(Object) methods
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.