Understanding ArrayList in Java

Understanding ArrayList in Java

4 mins read784 Views Comment
Updated on Aug 1, 2024 15:42 IST

The below article goes through explaining ArrayList in Java with suitable examples. It covers the creation and operations on ArrayList along with a few methods in it. Let’s begin!

arraylist in java

An ArrayList in Java is an array that resizes itself as needed. It is also popularly known as a resizable array. A typical implementation is when the array is full, the array doubles in size. 

Contents

Compare best Courses on Java Programming from Coursera, Udemy, and Udacity.

Recommended online courses

Best-suited Java courses for you

Learn Java with these high-rated online courses

– / –
6 weeks
15 K
3 months
2.05 K
3 months
– / –
170 hours
5.4 K
1 month
– / –
6 months
– / –
2 months
17 K
3 months
5.5 K
1 month

What is ArrayList in Java?

Read: Implementing Array in Java.

ArrayList is a class that implements the List interface inside the collection framework in Java.

image1

For more, Read: OOPs Concepts in Java.

Array Vs. ArrayList in Java

Array ArrayList
Static Dynamic
Fixed-size array Resizable array
It can be represented in Single dimensions or multiple dimensions. Represented in Single dimension only.
An array uses the length attribute to calculate the total size of the array. An ArrayList uses the size() method to calculate the total size of the ArrayList.
Faster speed because of fixed size. Comparatively slower because of its dynamic nature.
An array can contain both primitives and objects.  ArrayList cannot store primitives; it can only store objects. However, since Java 5, primitives are automatically converted into objects using autoboxing.

Also, Read: Data Types in Java – Primitive and Non-Primitive Data Types Explained

How to create an ArrayList in Java?

Before creating and using ArrayList, we have to import the Java.util.ArrayList package.

Syntax: 


 
ArrayList<Type> arrayList= new ArrayList<>();
Copy code

Example:


 
// create Integer(Wrapper class) type arraylist.
ArrayList<Integer> arrayList = new ArrayList<>();
// create String type arraylist.
ArrayList<String> arrayList = new ArrayList<>();
Copy code

Here, we have used the Integer Wrapper Class in Java to create an object of type integer. As ArrayList can’t use primitive datatype without converting it into objects.

Let’s take an example to see its implementation:


 
import java.util.ArrayList;
class Main {
public static void main(String[] args){
// create an Empty ArrayList
ArrayList<String> Shapes = new ArrayList<>();
System.out.println("ArrayList: " +Shapes);
}
}
Copy code

Explanation:

In the above code we created an empty ArrayList named Shapes.

Output:

output1

For more information: Method Overloading in Java

Operations on ArrayList

Following are some of the Operations on ArrayList–

Add elements

Let’s take an example to see the adding of elements in ArrayList.

Example:


 
import java.util.ArrayList;
class Main {
public static void main(String[] args){
// create an ArrayList
ArrayList<String> Shapes = new ArrayList<>();
// Add elements to ArrayList
Shapes.add("Rectangle");
Shapes.add("Circle");
Shapes.add("Triangle");
Shapes.add("Square");
System.out.println("ArrayList: " +Shapes);
}
}
Copy code

Explanation:

In the above code, we created an ArrayList named Shapes and added the elements using add() method. Hence, it displays an ArrayList with elements added.

Output:

output2

For more information: Method Overriding in Java

Access elements

Using the get() method with the argument as an index number, we can fetch or access the element at a desired position from the selected ArrayList.

Example:


 
import java.util.ArrayList;
class Main {
public static void main(String[] args){
// create an ArrayList
ArrayList<String> Shapes = new ArrayList<>();
// Add elements to ArrayList
Shapes.add("Rectangle");
Shapes.add("Circle");
Shapes.add("Triangle");
Shapes.add("Square");
System.out.println("ArrayList: " +Shapes);
// get the element at postion 2 from the arraylist
String str = Shapes.get(1);
System.out.print("Element at 2nd position: " + str);
}
}
Copy code

Explanation:

Here, we used Shapes.get(1) to fetch the element at index number one from Shapes ArrayList.

Output:

output3

Read: Loops in Java

Change elements

In order to change the elements in the ArrayList, we use the set() method with parameters such as index number and new element.

Example:


 
import java.util.ArrayList;
class Main {
public static void main(String[] args){
// create an ArrayList
ArrayList<String> Shapes = new ArrayList<>();
// Add elements to ArrayList
Shapes.add("Rectangle");
Shapes.add("Circle");
Shapes.add("Triangle");
Shapes.add("Square");
System.out.println("ArrayList: " +Shapes);
// Alter the element of the array list
Shapes.set(2, "Hexagon");
System.out.println("Modified ArrayList: " +Shapes);
}
}
Copy code

Explanation:

We used the set() method in the above code to alter the element at index 2 from Triangle to Hexagon.

Output:

Also, read: Strings in Java

Remove elements

We use the remove() method to delete the element whose index number is specified in the parameter of the method.

Example:


 
import java.util.ArrayList;
class Main {
public static void main(String[] args){
// create an ArrayList
ArrayList<String> Shapes = new ArrayList<>();
// Add elements to ArrayList
Shapes.add("Rectangle");
Shapes.add("Circle");
Shapes.add("Triangle");
Shapes.add("Square");
System.out.println("ArrayList: " +Shapes);
// remove element from index 2
String str = Shapes.remove(2);
System.out.println("Updated ArrayList: " +Shapes);
System.out.println("Removed Element: " + str);
}
}
Copy code

Explanation:

In the above code, we used the remove() method to delete the element at a specified index number.

Output:

output4

Read: Access Modifiers in Java

Methods of ArrayList Class

Following are a few commonly used methods in the ArrayList class:

Methods Descriptions
size() It returns the length of the ArrayList.
sort() It sorts the ArrayList elements.
clone() Creates another ArrayList with the same element, size, and capacity.
contains() Searches the ArrayList for the specified element and returns a boolean result.
ensureCapacity() Specifies the total number of the element the ArrayList can take. Hence, it sets the size of an ArrayList with the specified capacity.
isEmpty() Checks if the arraylist is empty or not.
indexOf() It searches a specified (entered) element in an ArrayList and returns the element’s index.
clear() Removes all the elements from the ArrayList.

 

Multithreading in Java
Abstract Class in Java
Super Keyword in Java

Let’s see an example to visit the implementation of the above methods.

Example:


 
import java.util.ArrayList;
import java.util.Comparator;
class Main {
public static void main(String[] args){
// create an ArrayList
ArrayList<String> Shapes = new ArrayList<>();
// Add elements to ArrayList
Shapes.add("Rectangle");
Shapes.add("Circle");
Shapes.add("Triangle");
Shapes.add("Square");
System.out.println("ArrayList: " +Shapes);
// Size of the ArrayList
System.out.println("Size of the ArrayList: " +Shapes.size());
// Sorted ArrayList
Shapes.sort(Comparator.naturalOrder());
System.out.println("Sorted Ascending ArrayList: " +Shapes);
Shapes.sort(Comparator.reverseOrder());
System.out.println("Sorted Reverse ArrayList: " +Shapes);
// create copy of ArrayList Shapes
ArrayList<Integer> cloneShapes = (ArrayList<Integer>)Shapes.clone();
System.out.println("Cloned ArrayList: " + cloneShapes);
// checks if circle is present in the arraylist
System.out.print("Is Circle present in the arraylist: ");
System.out.println(Shapes.contains("Circle"));
// set the capacity of the arraylist
Shapes.ensureCapacity(10);
// checks if the ArrayList is empty
boolean result = Shapes.isEmpty(); // false
System.out.println("Is the ArrayList Shapes empty? " + result);
// find the position of Square
int pos = Shapes.indexOf("Square");
System.out.println("Index of element Square: " + pos);
//clear the cloneShapes ArrayList
cloneShapes.clear();
}
}
Copy code

Output:

output5

Also Read: Difference between JDK, JRE, and JVM

Iterate through an ArrayList

We can iterate through the ArrayList using for-each loop.

Example:


 
import java.util.ArrayList;
class Main {
public static void main(String[] args){
// create an ArrayList
ArrayList<String> Shapes = new ArrayList<>();
// Add elements to ArrayList
Shapes.add("Rectangle");
Shapes.add("Circle");
Shapes.add("Triangle");
Shapes.add("Square");
System.out.println("ArrayList: " +Shapes);
// iterate the ArrayList using for-each loop
System.out.println("Accessing individual elements in Shapes ArrayList: ");
for (String sh : Shapes) {
System.out.println(sh);
}
}
}
Copy code

Output:

output6

Conclusion

I hope the above article helped you build a concrete understanding of ArrayList in Java. You can read more topics to gain knowledge of concepts related to Java.

For more, Read: 8 Most Important Data Structures a Programmer Must Know 

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio