Training Outcomes Within Your Budget!

We ensure quality, budget-alignment, and timely delivery by our expert instructors.

Share this Resource

Table of Contents

ArrayList in Java

Are you looking to manage data collections with ease and flexibility in your Java applications? ArrayList in Java is a powerful tool that offers dynamic sizing and simple methods to store, access, and manipulate data efficiently. It's perfect for developers seeking a more adaptable alternative to traditional arrays.

Imagine being able to effortlessly handle large datasets without worrying about fixed sizes or cumbersome operations. With ArrayList in Java, you can enhance your coding efficiency and streamline your development process.

Read this blog to learn about ArrayList in Java, with examples utilising technologies like HTML, CSS, JavaScript, SQL, Python, PHP, and Bootstrap. Discover how mastering ArrayList can enhance your programming skills.

Table of contents  

1) What is an ArrayList?

2) Important Features of ArrayList in Java

3) Constructors of ArrayList

4) How to Create an ArrayList?

5) How to Add and Remove Elements in Java?

6) Accessing Elements

7) ArrayList Methods

8) ArrayList vs Arrays

9) When to use ArrayList?

10) Advantages of Java ArrayList

11) Disadvantages of Java ArrayList

12) Conclusion

What is an ArrayList? 

An ArrayList is a dynamic array-like data structure in Java that belongs to the Java Collections Framework. It is part of the ‘java.util’ package and provides a flexible and convenient way to store and manipulate a collection of elements. Unlike traditional arrays in Java, ArrayLists can dynamically grow or shrink in size as needed, making them well-suited for scenarios where you need a collection of elements that can change in size. 
 

Java Courses
 

Important Features of ArrayList in Java 

Arraylist has several key features. Some of them are mentioned below.

1) Inheritance and Implementation: Inherits from the AbstractList class and implements the List interface.

2) Dynamic Sizing: Initialised with a specific size but automatically adjusts as the collection grows or shrinks.

3) Random Access: Allows random access to elements.

4) Wrapper Classes: Cannot be used for primitive types (like int or char) without wrapper classes.

5) C++ Equivalent: This can be seen as a Java equivalent to a vector in C++.

6) Synchronisation: ArrayList is not synchronised; use Vector for a synchronised version.

Let's explore more about Java ArrayList with the following illustration:

Java ArrayList illustration 

In the illustration given above, AbstractList, CopyOnWriteArrayList, and AbstractSequentialList are classes implementing the List interface, each with unique functionalities. Let’s learn more about them below:

1) AbstractList: Used to implement an unmodifiable list. To utilise it, extend the AbstractList class and implement the get() and size() methods.

2) CopyOnWriteArrayList: An enhanced version of ArrayList where modifications (add, set, remove) create a fresh copy of the list.

3) AbstractSequentialList: Implements the Collection interface and the AbstractCollection class and is used to implement an unmodifiable list by extending AbstractList and implementing get() and size() methods.

Constructors of ArrayList

To create an ArrayList, you need to instantiate an object of the ArrayList class. This class offers various constructors for different initialisation scenarios:

1) ArrayList()

a) This constructor creates an empty ArrayList.

b) Example:

ArrayList arr = new ArrayList();

2) ArrayList(Collection c)

a) This constructor initialises the ArrayList with elements from the specified collection c.

b) Example

ArrayList arr = new ArrayList(c);

3) ArrayList(int capacity)

a) This constructor initialises the ArrayList with a specified initial capacity.

b) Example

ArrayList arr = new ArrayList(N);

Master Java Engineering and transform your career – register for our Java Engineer Training now! 

How to Create an ArrayList?

Creating an ArrayList in Java is straightforward. Here's how you can create one: 

1) Import the ArrayList class

Make sure you import the ArrayList class from the java.util package at the top of your Java file: 

import java.util.ArrayList; 

2) Declare an ArrayList 

Declare a variable of type ArrayList with the data type of the elements you want to store. For example, if you want to create an ArrayList of integers: 

ArrayList myArrayList = new ArrayList(); 

This line creates an empty ArrayList that can hold Integer objects. 

3) Initialise the ArrayList (optional):  

You can also initialise an ArrayList with initial elements by providing them in the constructor. For example: 

ArrayList names = new ArrayList(Arrays.avssList("Alice", "Bob", "Charlie")); 

This line creates an ArrayList of Strings and initialises it with three elements. 

Here's a complete example: 

import java.util.ArrayList; 

import java.util.Arrays; 

public class ArrayListExample { 

    public static void main(String[] args) { 

        // Create an empty ArrayList of integers 

        ArrayList numbers = new ArrayList(); 

        // Initialise an ArrayList of strings with elements 

        ArrayList names = new ArrayList(Arrays.asList("Alice", "Bob", "Charlie")); 

    } 

Now you have an ArrayList ready to use, either empty or pre-initialised with data, depending on your requirements. You can start adding, removing, and accessing elements as needed. 

Empower your future with Java Training – Join us today! 

How to add and Remove Elements 

You can not only add but also remove elements from an ArrayList in Java using various methods provided by the ArrayList class. Here's how to do it:

1) Adding Elements

import java.util.ArrayList;

public class ArrayListExample {

    public static void main(String[] args) {

        // Create an ArrayList of String type

        ArrayList list = new ArrayList<>();

        // Add elements to the ArrayList

        list.add("Element 1");

        list.add("Element 2");

        list.add("Element 3");

        // Display the elements in the ArrayList

        System.out.println("ArrayList: " + list);

    }

You can define the index at which you want to insert an element using the add(index, element) method.

import java.util.ArrayList; 

public class ArrayListExample {

    public static void main(String[] args) {

        // Create an ArrayList of String type

        ArrayList list = new ArrayList<>();

        // Add initial elements to the ArrayList

        list.add("Element 1");

        list.add("Element 2");

        list.add("Element 4");

        // Insert an element at a specific index

        list.add(2, "Element 3"); // Inserts "Element 3" at index 2

        // Display the elements in the ArrayList

        System.out.println("ArrayList: " + list);

    }

}

2) Removing Elements

1) remove(index) Method 

You can remove an element at a particular index using the remove(index) method. This method returns the removed element. 

import java.util.ArrayList; 

public class ArrayListExample {

    public static void main(String[] args) {

        // Create an ArrayList of Integer type

        ArrayList numbers = new ArrayList<>(); 

        // Add elements to the ArrayList

        numbers.add(10);

        numbers.add(20);

        numbers.add(30); 

        // Display the ArrayList before removal

        System.out.println("ArrayList before removal: " + numbers);

        // Remove the element at index 1 and store the removed element

        int removed = numbers.remove(1); // Removes and returns the element at index 1 (20) 

        // Display the removed element

        System.out.println("Removed element: " + removed); 

        // Display the ArrayList after removal

        System.out.println("ArrayList after removal: " + numbers);

    }

2) remove(object) Method 

You can remove the first occurrence of a specific object using the remove(object) method.

import java.util.ArrayList; 

public class ArrayListExample {

    public static void main(String[] args) {

        // Create an ArrayList of String type

        ArrayList names = new ArrayList<>(); 

        // Add elements to the ArrayList

        names.add("Alice");

        names.add("Bob");

        names.add("Charlie"); 

        // Display the ArrayList before removal

        System.out.println("ArrayList before removal: " + names); 

        // Remove the first occurrence of "Bob"

        names.remove("Bob"); 

        // Display the ArrayList after removal

        System.out.println("ArrayList after removal: " + names);

    }

3) clear() Method 

To remove all elements and empty the ArrayList, use the clear() method.

import java.util.ArrayList;

public class ArrayListExample {

    public static void main(String[] args) {

        // Create an ArrayList of Double type

        ArrayList prices = new ArrayList<>(); 

        // Add elements to the ArrayList

        prices.add(9.99);

        prices.add(19.99); 

        // Display the ArrayList before clearing

        System.out.println("ArrayList before clearing: " + prices); 

        // Remove all elements and empty the ArrayList using clear() method

        prices.clear(); 

        // Display the ArrayList after clearing

        System.out.println("ArrayList after clearing: " + prices);

    }

}

Accessing Elements

Accessing elements in an ArrayList in Java is simple. You can retrieve elements by their index, iterate through the ArrayList, or use various methods provided by the ArrayList class. Here's how you can access elements:

1) Accessing Elements by Index

You can access elements in an ArrayList by specifying their index, which starts at 0 for the first element and goes up to size() - 1 for the last element. Here's an example:

import java.util.ArrayList; 

public class ArrayListExample {

    public static void main(String[] args) {

        // Create an ArrayList of String type

        ArrayList fruits = new ArrayList<>();

        // Add elements to the ArrayList

        fruits.add("Apple");

        fruits.add("Banana");

        fruits.add("Cherry");

        // Access the first element ("Apple")

        String firstFruit = fruits.get(0);

        System.out.println("First fruit: " + firstFruit); 

        // Access the second element ("Banana")

        String secondFruit = fruits.get(1);

        System.out.println("Second fruit: " + secondFruit);

    }

2) Iterating Through the ArrayList

You can use loops, such as a for-each loop or a regular for loop, to iterate through all the elements in the ArrayList.
 

import java.util.ArrayList; 

public class ArrayListExample {

    public static void main(String[] args) {

        // Create an ArrayList of String type

        ArrayList fruits = new ArrayList<>(); 

        // Add elements to the ArrayList

        fruits.add("Apple");

        fruits.add("Banana");

        fruits.add("Cherry"); 

        // Using a For-Each Loop

        System.out.println("Using a For-Each Loop:");

        for (String fruit : fruits) {

            System.out.println(fruit); // This will print each fruit one by one

        } 

        // Using a Regular For Loop

        System.out.println("nUsing a Regular For Loop:");

        for (int i = 0; i < fruits.size(); i++) {

            String fruit = fruits.get(i);

            System.out.println(fruit); // This will also print each fruit one by one

        }

    }

3) Checking for Element Existence

You can efficiently check if an element exists in the ArrayList using the contains() method:

import java.util.ArrayList; 

public class ArrayListExample {

    public static void main(String[] args) {

        // Create an ArrayList of String type

        ArrayList fruits = new ArrayList<>();

        // Add elements to the ArrayList

        fruits.add("Apple");

        fruits.add("Banana");

        fruits.add("Cherry"); 

        // Check if the ArrayList contains "Banana"

        boolean containsBanana = fruits.contains("Banana"); 

        // Print a message if "Banana" is found

        if (containsBanana) {

            System.out.println("The ArrayList contains 'Banana'.");

        } else {

            System.out.println("The ArrayList does not contain 'Banana'.");

        }

    }

}

4) Getting the Index of an Element

To find the index of a specific element in the ArrayList, you can use the indexOf() method. It returns the index of the first occurrence of the element, or -1 if the element is not present:

import java.util.ArrayList; 

public class ArrayListExample {

    public static void main(String[] args) {

import java.util.ArrayList; 

public class ArrayListExample {

    public static void main(String[] args) {

        // Create an ArrayList of String type

        ArrayList fruits = new ArrayList<>(); 

        // Add elements to the ArrayList

        fruits.add("Apple");

        fruits.add("Banana");

        fruits.add("Cherry"); 

        // Find the index of "Cherry"

        int indexOfCherry = fruits.indexOf("Cherry"); 

        // Print the index if "Cherry" is found

        if (indexOfCherry != -1) {

            System.out.println("The index of 'Cherry' is: " + indexOfCherry);

        } else {

            System.out.println("'Cherry' is not found in the ArrayList.");

        }

    }

}

Remember that when accessing elements by index, be sure to check if the index is within the valid range (0 to size() - 1) to avoid IndexOutOfBoundsException errors. 

ArrayList Methods

Here are some common methods for working with ArrayLists in Java: 

1) Common ArrayList Methods

1) add(E element): Adds an element to the end of the ArrayList. 

2) add(int index, E element): Inserts an element at the specified index. 

3) get(int index): Retrieves the element at the given index. 

4) set(int index, E element): Replaces the element with a new element.

5) remove(int index): Removes and returns the element at the specified index. 

6) size(): Returns the number of elements in the ArrayList. 

7) isEmpty(): Checks if the ArrayList is empty. 

8) clear(): Removes all elements from the ArrayList. 

2) Iterating Through an ArrayList

You can iterate through an ArrayList using various loops or enhanced for-each loops. Here's an example using a for-each loop:

import java.util.ArrayList; 

public class ArrayListExample {

    public static void main(String[] args) {

        // Create an ArrayList of String type

        ArrayList fruits = new ArrayList<>(); 

        // Add elements to the ArrayList

        fruits.add("Apple");

        fruits.add("Banana");

        fruits.add("Cherry");

        // Using a For-Each Loop to print each element

        for (String fruit : fruits) {

            System.out.println(fruit);

        }

    }

}

You can also use a regular for loop with an index to access elements one by one. 

3) Sorting an ArrayList 

To sort an ArrayList, you can use the Collections.sort() method, which is a part of the java.util package. Make sure the elements in the ArrayList implement the Comparable interface or provide a custom Comparator for sorting. 

Here's an example of sorting an ArrayList of strings: 

import java.util.Collections; 

public class ArrayListExample {

    public static void main(String[] args) {

        // Create an ArrayList of String type

        ArrayList fruits = new ArrayList<>();

        // Add elements to the ArrayList

        fruits.add("Cherry");

        fruits.add("Apple");

        fruits.add("Banana") 

        // Sort the ArrayList

        Collections.sort(fruits); 

        // Using a For-Each Loop to print each sorted element

        for (String fruit : fruits) {

            System.out.println(fruit);

        }

    }

}

This code sorts the fruits ArrayList in natural order (lexicographically). If you want to sort in a custom order, you can provide a custom Comparator to the Collections.sort() method. 

These are some of the common ArrayList methods and ways to iterate through and sort an ArrayList in Java. ArrayLists are versatile data structures that offer various methods for manipulating and processing elements. 

ArrayList vs Arrays 

ArrayLists and arrays are both used for storing collections of elements in Java, but they have distinct characteristics that make each more suitable for different use cases. Here’s a comparison between the two:

1) ArrayList

1) Dynamic Sizing: ArrayLists can grow or shrink as elements are added or removed, unlike arrays, which require a predefined size. No need to specify the size in advance.

2) Automatic Resizing: When an ArrayList reaches its capacity, it automatically resizes itself, reallocating memory as needed. You don't have to manage this manually. 

3) Add and Remove Elements: Adding and removing elements from an ArrayList is easy, and the ArrayList takes care of resizing. 

4) Type Safety: You can use generics to ensure type safety. For example, ArrayList ensures that only integers are stored. 

5) Methods: ArrayLists provide methods for various operations like adding, removing, sorting, and checking for element existence. 

6) Iterating: You can easily iterate through an ArrayList using loops or iterators. 

2) Arrays  

1) Fixed Size: Arrays have a fixed size, requiring you to specify the size upon creation. Once established, their size cannot be altered.

2) Manual Sizing: You have to manage the array size yourself. If you need more space, you must create a new array of larger sizes and copy the elements from the old one.  

3) Efficiency: Arrays can be more memory and time-efficient in some cases because they don't have the overhead of dynamically resizing. 

4) Not Type-safe: Arrays are not inherently type-safe, allowing you to store elements of different types within the same array. 

5) No built-in Methods: Arrays don't have built-in methods for common operations. You need to write custom code to add, remove, or sort elements. 

6) Iterating: Iterating through arrays is similar to ArrayLists, using loops or indices. 

When to Use ArrayList?

When to Use ArrayList

ArrayLists are a dynamic and flexible data structure in Java, and they are suitable for a variety of use cases. You should consider using ArrayLists in the following situations: 

1) Dynamic Sizing: ArrayLists can grow or shrink as elements are added or removed, unlike arrays which require a predefined size. No need to specify the size in advance.

2) Convenience: If you want to use a collection that provides built-in methods for adding, removing, and manipulating elements without writing custom code. 

3) Type Safety: If you want to ensure type safety, you can use generics with ArrayLists. For example, you can create an ArrayList to store only integers. 

4) Collections Framework: When working with Java's Collections Framework, ArrayList is a part of it and provides a consistent way to work with collections alongside other data structures like LinkedList, HashMap, and HashSet. 

5) Data Retrieval and Iteration: When you need to access elements by their index or iterate through the elements using loops, such as for-each or for loops. 

6) Avoiding Manual Memory Management: If you prefer to avoid manual memory management, ArrayList automatically handles resizing as needed, ensuring efficient memory use without your intervention.

7) Unknown or Variable Collection Size: When the size of your collection is not known in advance or when it might change over time. 

8) Working with Lists: ArrayList is an excellent choice when you need list-like behaviour, such as maintaining an ordered collection of elements.

9) Ease of use: For quick and easy implementation of dynamic data structures, especially in situations where you don't need low-level memory control. 

10) Compatibility: When you need to work with libraries or APIs that expect collections as input or return values. ArrayList is widely supported in Java libraries and APIs. 

Advantages of Java ArrayList

Let’s take a look at different advantages of Java ArrayLIst:

1) Dynamic Size: ArrayLists can grow and shrink as needed, making it simple to add or remove elements.

2) Ease of Use: ArrayList is user-friendly. This makes it a popular choice among Java developers

3) Fast Access: Provides quick access to elements as it is implemented with an underlying array.

4) Ordered Collection: ArrayList maintains the order of elements, allowing you to access them in the sequence they were added. 

5) Supports Null Values: Can store null values, which is useful for representing the absence of an element.

Disadvantages of Java ArrayList

Let’s take a look at different disadvantages of Java ArrayLIst:  

1) Slower than Arrays: ArrayLists are slower for operations like inserting elements in the middle of the list compared to arrays.

2) Increased Memory Usage: Requires more memory than arrays due to maintaining dynamic sizing and handling resizing.

3) Not Thread-Safe: Multiple threads accessing and modifying the list concurrently can cause race conditions and data corruption.

4) Performance Degradation: Performance may decline as the list grows, especially when searching and inserting elements in the middle.

Conclusion 

ArrayLists in Java are a fundamental and flexible data structure that offers numerous advantages for managing collections of elements. They are part of the Java Collections Framework and provide a dynamic, resizable array-like structure. This makes them a versatile choice for a wide range of applications.

Ready to elevate your web development skills? Join our Web Development Using Java Training today! 

Frequently Asked Questions

What is Difference Between Java ArrayList and LinkedList? faq-arrow

ArrayList uses a dynamic array for storing elements, providing fast random access and efficient indexing. LinkedList uses a doubly linked list, allowing for efficient insertions and deletions. ArrayList is better for frequent read operations, while LinkedList is better for frequent insertions and deletions.

Why Use ArrayList Over Array? faq-arrow

ArrayList offers dynamic sizing, which means it can grow and shrink as needed, unlike arrays with fixed size. It also provides useful methods for manipulating elements, such as adding, removing, and searching, making it more flexible and convenient for managing collections of data.

What are the Other Resources and Offers Provided by The Knowledge Academy? faq-arrow

The Knowledge Academy takes global learning to new heights, offering over 30,000 online courses across 490+ locations in 220 countries. This expansive reach ensures accessibility and convenience for learners worldwide. 

Alongside our diverse Online Course Catalogue, encompassing 17 major categories, we go the extra mile by providing a plethora of free educational Online Resources like News updates, Blogs, videos, webinars, and interview questions. Tailoring learning experiences further, professionals can maximise value with customisable Course Bundles of TKA
 

What is The Knowledge Pass, and How Does it Work? faq-arrow

The Knowledge Academy’s Knowledge Pass, a prepaid voucher, adds another layer of flexibility, allowing course bookings over a 12-month period. Join us on a journey where education knows no bounds. 

What are the Related Courses and Blogs Provided by The Knowledge Academy? faq-arrow

The Knowledge Academy offers various Java Courses, including the JavaScript for Beginners Course, Java Swing Development Training, and Java Engineer Training. These courses cater to different skill levels, providing comprehensive insights into Django Alternatives

Our Programming & DevOps Blogs cover a range of topics related to JavaScript, offering valuable resources, best practices, and industry insights. Whether you are a beginner or looking to advance your Programming and DevOps skills, The Knowledge Academy's diverse courses and informative blogs have got you covered.

Upcoming Programming & DevOps Resources Batches & Dates

Date

building Java Programming

Get A Quote

WHO WILL BE FUNDING THE COURSE?

cross

BIGGEST
Christmas SALE!

red-starWHO WILL BE FUNDING THE COURSE?

close

close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.

close

close

Press esc to close

close close

Back to course information

Thank you for your enquiry!

One of our training experts will be in touch shortly to go overy your training requirements.

close close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.